Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Rendering Different Components

Let's say I'm building a react application that changes content inside a box with a button click in this manner(Clicking the same button):

Click 1: Component 1
Click 2: Component 2
Click 3: Component 3
Click 4: Component 1
Click 5: Component 2
Click 6: Component 3

So the obvious way to do this would be via states, and in the render method render the component you wish according to what the state is. But I don't wish to rerender every component. That is, on the button click, I just want the previous component to become invisible, and display the new element.

This is easy to do in simple normal HTML/CSS/JS:

display:none;

But how would one approach this in react, and why would it be better/more efficient than just doing it normally?

Not necessarily looking for full code, more of an understanding of what to do.

Thanks in advance!

like image 208
idude Avatar asked Nov 25 '25 19:11

idude


1 Answers

Maintain a counter as an state and increment it on every click, based on that value you can conditionally add styles to your component eg

 onClick={() => {
     this.setState((prevState) => (
            {counter: (prevState.counter + 1)%3)}
             )
    )}
 } 

and then in the component style which you need to apply internally on component outermost div

<Component1 style={(this.state.counter == 0)? {display: 'block'}: {display: 'none'}}/>

And in Component1

render() {
    return <div style={this.props.style}>{/* Content Here */}</div>
}

Also since React maintains a Virtual DOM for updates, it is more efficeint and fast in rendering contents

like image 125
Shubham Khatri Avatar answered Nov 27 '25 09:11

Shubham Khatri