How To Find And Modify DOM Nodes In The React Before Render?
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?
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>
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?