Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to dynamically select components in React

Tags:

reactjs

I'm super new to React and I have two components I want to toggle between based on a user click. I've went about it by creating a 'currentView' state and using that to set/update what the user should be looking at, but when I try to get the components to display it throws tag errors. Here's my code:

class App extends Component {
  constructor(props){
    super(props);

    this.state={
      currentView: "Welcome",
    };
  }

  goTrack() {
    this.setState({currentView: "Tracker"});
    console.log(this.state.currentView);
  }

  goReview() {
    this.setState({currentView: "Review"});
    console.log(this.state.currentView);
  }

  render() {
    return (
      <div className="App">
        <aside>
          <nav>
            <ul>
              <li onClick={()=>this.goTrack()}> Tracker </li>
              <li onClick={()=>this.goReview()}> Review </li> 
            </ul>
          </nav>
        </aside>
        <main>  
         <this.state.currentView/>
        </main>
      </div>
    );
  }
}

export default App;

My question is how should I go about dynamically selecting components to display without re-rendering the entire DOM?

like image 396
Melvin Jensen Avatar asked Dec 05 '25 13:12

Melvin Jensen


1 Answers

One way to solve this is to use the current state to match a key in an object containing the component you want in a certain state.

constructor() {
  super()
  this.state = {
    current: 'welcome',
  }
}


render() {
  const myComponents = {
    welcome: <Welcome />,
    tracker: <Tracker />,
  }
  const CurrentComponent = myComponents[this.state.current]

  return (
    <CurrentComponent />
  )
}

And when you change the state current with the value 'tracker', Tracker component will be rendered instead of Welcome component.

like image 166
J.Lindebro Avatar answered Dec 07 '25 09:12

J.Lindebro