Grant Kochmann
Grant Kochmann

Reputation: 179

Programmatically change react component being displayed

I'm trying to have a page that switches out which component is rendered based off of a pair of navigation buttons. The page is set up like this

ReactDOM.render(<Logo/>, document.getElementById('logo'));
ReactDOM.render(<Upload/>, document.getElementById('main'));
ReactDOM.render(<NavButtons/>, document.getElementById('nav_buttons'))
ReactDOM.render(<Footer />, document.getElementById('footer'));

The <Upload/> component is the one I wish to cycle out. So when the user pressed the 'next' navigation button a different component would then be loaded on the page.

How do you go about this? Am I attacking this problem correctly? I am new to react so trying to figure out the best way to utilize it.

Ended up using both answers below for different use cases. Both work to accomplish this though.

Upvotes: 2

Views: 1240

Answers (2)

Mukesh Burnwal Mike
Mukesh Burnwal Mike

Reputation: 499

Use react router and dynamically update the Link in next button then you will able to get the next component

Example:-

    constructor(props){
    super(props);
    this.increaseIndexValue=this.increaseIndexValue.bind(this);
    this.state = {
      "nextIndex":1,
      "componentArray" : ["Logo", "Upload", "NavButtons", "Footer"],
    }
    increaseIndexValue(){
    const {nextIndex, componentArray} = this.state;
    if(nextIndex == 1){
        this.setState((prevState) => {
          return {nextIndex: prevState.nextIndex + 1}
        });
    }
    else if (nextIndex >1 && nextIndex < componentArray.length-1) {
      this.setState((prevState) => {
        return {nextIndex: prevState.nextIndex + 1}
      });
    }
    else if (nextIndex == componentArray.length -1) {
      this.setState((prevState) => {
        return {nextIndex: 3 }
      });
    }
  }
    <Router>
            <Route exact path="/" component={Logo} />
            <Route path="/Logo" component={Logo} />
            <Route path="/Upload" component={Upload} />
            <Route path="/NavButtons" component={NavButtons} />
            <Route path="/Footer" component={Footer} />
         <Link to={"/"+componentArray[nextIndex]}><a href="" className="next" onClick={this.increaseIndexValue}>Next &raquo;</a></Link>

      </Router>

Upvotes: 3

Manoj Kumar
Manoj Kumar

Reputation: 176

Your use case can be achieved by changing the internal state of the parent container on user clicks and rendering different child components by checking which component to render based on the state value.

Since, you are new to react, I don't even know if u get the point. Go through react docs about state, props and lifecycles before starting to code in react.

https://reactjs.org/docs/state-and-lifecycle.html

Upvotes: 3

Related Questions