I am trying to toggle a content on my page with a button in React.js If I press the button, I want the content to disappear. If I press it again, I want the content to reappear again. I tried everything that I can think of, but nothing seems to work. I initially tried a ternary statement to see if I can toggle, but it just breaks my application. Can someone tell me how I can improve this part of the project? Here is what I have:
//App.js
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isToggle: false
};
}
handleClick(e) {
this.setState({ !isToggle ? isToggle: true : isToggle: false });
}
render() {
const style = {
display: none
};
return (
<div>
<h1 className="text-xs-center">List of items:</h1>
<button onClick={this.handleClick.bind(this)} className="btn btn-primary">Toggle</button>
<div className="container" style={!isToggle ? style.display = none : style.display = block}>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</div>
</div>
);
}
}
export default App;
Basically, I want to toggle the Item 1, Item 2, Item 3, Item 4.
This would be its shape if I were to make up the component.
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {isToggle: false};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.setState({isToggle: !this.state.isToggle});
}
render() {
return (
<div>
<h1 className="text-xs-center">List of items:</h1>
<button
className="btn btn-primary"
onClick={this.handleClick}
>
Toggle
</button>
<div
style={{display: this.state.isToggle ? 'block': 'none'}}
className="container"
>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</div>
</div>
);
}
}
export default App;
You can use conditional rendering instead of CSS:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isVisible: false
};
this.onToggle = this.onToggle.bind(this);
}
onToggle(e) {
this.setState({isVisible: !this.state.isVisible});
}
render() {
return (
<div>
<h1 className="text-xs-center">List of items:</h1>
<button onClick={this.onToggle} className="btn btn-primary">Toggle</button>
{this.state.isVisible &&
<div className="container">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</div>
}
</div>
);
}
}
export default App;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With