React js Update State onclick Example Tutorial
In this article, we will know about how to update state onclick event handler in react js. A state is one type of object variable. here we will understand with a simple example that how to update the state.
So you can see the following example.
React Updating State With Class Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; class App extends Component { constructor(props) { super(props); this.state = { showModal: false }; this.open = this.open.bind(this); } open() { this.setState({showModal: true}); } render() { return ( <Button onClick={this.open}>Open Modal</Button> ); } } export default App; |
React Updating State With Functional Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import React, {useState} from 'react'; import logo from './logo.svg'; import './App.css'; import { Button } from 'react-bootstrap'; function App() { const [showModal, setShow] = useState(false); const open = () => setShow(true); return ( <Button onClick={this.open}>Open Modal</Button> ); } export default App; |
Please follow and like us: