Reputation: 27
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'));
Upvotes: 1
Views: 431
Reputation: 111
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 :)
Upvotes: 3