- Create Components folder under src folder
- Add ToggleExp1.js file and add below Code
import React, { Component } from 'react';
class ToggleExp1 extends Component {
state = {
showDiv: false
}
toggleDivHandler = () => {
const doesShow = this.state.showDiv;
this.setState( { showDiv: !doesShow } );
}
render () {
let divData = null;
if ( this.state.showDiv ) {
divData = (
<div>
My Data
</div>
);
}
return (
<div className="App">
<h1>Toggle Example</h1>
<button
onClick={this.toggleDivHandler}>Toggle Div</button>
{divData}
</div>
);
}
}
export default ToggleExp1;
- Open App.js file and update code as below
import React from 'react';
import './App.css';
import ToggleExp1 from './Components/ToggleExp1'
function App() {
return (
<div className="App">
<ToggleExp1/>
</div>
);
}
export default App;
Output:
No comments:
Post a Comment