1

I am a beginner in the React and I am trying to make a sidebar with a navigation menu. When user click on the li tag with className "frist", the component FrstComponent opens, when user click on the li tag with className "second" SecondComponent opens etc. Like bootstrap tabs. This is my code

    class Navigation extends React.Component {
 constructor(props) {
    super(props)
    this.state = {
       isActive: "first"
    }
    this.handleClickChange =this.handleClickChange.bind(this)
  }

  handleClickChange(){
    this.setState={
        isActive: !this.state.isActive
    }
  }

  render() {
    const {active} = this.state.isActive
    if(active === 'first'){
      return <FristComponent/>
    }
    if(active === 'second'){
      return <SecondComponent/>
    }
    return (
      <div>
      <ul>
        <li 
        className="first"
        onClick={this.handleClickChange} 
        >
          FIRST

        </li>
        <li 
          className="second"   
          onClick={this.handleClickChange}
          >
          SECOND
        </li>
        <li className="third">THIRD</li>
        <li className="fourth">FOURTH</li>
        <li className="fifth">FIFTH</li>
      </ul>

      </div>
    )
  }
}

React.render(<Navigation />, document.getElementById('app'));
1

1 Answer 1

3

i'm trying to help you, but your code need more refactoring :)

import React from "react"
import ReactDOM from "react-dom";

class Navigation extends React.Component {
  state = {
    active: "first"
  }

  handleClickChange = e => {
    const { className } = e.target

    this.setState({ active: className})
  }

  render() {
    const { active } = this.state

    return (
      <div>
        {active === 'first' && <div>First Component</div>}

        {active === 'second' && <div>Second Component</div>}

        <ul>
          <li className="first"
            onClick={this.handleClickChange}
          >
            FIRST

        </li>
          <li
            className="second"
            onClick={this.handleClickChange}
          >
            SECOND
        </li>
          <li className="third">THIRD</li>
          <li className="fourth">FOURTH</li>
          <li className="fifth">FIFTH</li>
        </ul>

      </div>
    )
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Navigation />, rootElement);

You need to pass on className to state and check this variable when you rendering. If you have a questions by this code, you can ask :)

1
  • Just a little note for you while saying constructor(props) and super(props) and this.state is perfectly valid what he has above "state = { active: "first"} " 100% the same but it is syntax sugar and does the constructor and super for you by running it through babel Commented Mar 5, 2019 at 21:28

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.