Ad

How To Find And Modify DOM Nodes In The React Before Render?

- 1 answer

i cound't see right way how to find and modify React DOM nodes before render. For example i need to make all founded images inside component as lazy load. But the problem is that I don't know which nodes will be inserted by the user. Therefore, I need to look for them after the user places nodes in the component, by using componentWillMount or constructor i think...

Actually in jQuery, to replace real src after user insereted it in. I will do something like this:

jQuery('.wrapper img').each(element => {
    let realSrc = element.attr('src')
    element
        .attr('data-real-src', realSrc)
        .attr('src', './fakeimage.png')
})

So in the React, i have to do something like this i think...

const modifiedChildren = children.reduce((arr, next) => {
    let modified = {
        ...next,
        src: './fakeimage.png',
        'data-real-src': next.src
    }
    return [
        ...arr,
        modified
    ]
}, [])

render {
    <div className="wrapper">{ modifiedChildren }</div>
}

Can you navigate me some please?

Ad

Answer

Stop thinking in DOM nodes. Start thinking in components.

You want a new component LazyLoadedImage which gets the real URL and displays it after some trigger. Something like that:

import fakeImage from 'assets/fakeimage.png';

const LazyLoadedImage = ({url, displayActualImage, ...props}) => {
    if(displayActualImage) return <img {...props} src={url}>;
    else return <img {...props} src={fakeImage}>;
}

Usage example:

<Slider>
    {images.map((obj, index) =>
     <LazyLoadedImage className='slider__img' url={obj.largeImageURL}
                      alt={obj.tags || 'cap'} key={index}/>)}
</Slider>
Ad
source: stackoverflow.com
Ad