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

Learn Something New Everyday,
Connect With The Best Developers!

Sign Up Now!

& 500k+ others use Hashnode actively.

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.

Anand Reddy Rikka's photo

A Continuous Learner and passionate coder

@pdavis For example like adding css/removing css for the component, listeners etc..

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

Want to read more?

Browse featured discussions

© 2020 · Hashnode