What is the best place to do DOM manipulations in ReactJS?

Comments (4)

Add a comment
Philip Davis's photo

You should let ReactJS do all the DOM manipulation for you. What are you trying to accomplish?

If you really need to mess with the DOM, an ideal place is in componentDidMount and then undo it in componentWillUnmount.

Show all replies
Lorefnon's photo

Open Web Enthusiast

For such cases, re-rendering the component is almost always the best option.

Philip Davis's photo

for adding/removing css classes, you could do something like this:

 render() {
     return <div className={ getClassName() }>...</div>;
 }

Where getClassName() calculates the value based on current state/props. Can also do this for style:

 render() {
     const { opacity, color } = this.state;
     return <div style={{ opacity, color }}>...</div>;
 }

For event listeners you'd generally use the built-in handlers e.g. onClick. But sometimes you need to work outside the box. e.g.

 componentDidMount() {
     $(ref).someJQueryPlugin({ /* options */ });
 }

 componentWillUnmount() {
     // Dispose of side effect caused by plugin
 }