Firstly, create an index.html file where the React application will be rendered:
- Create a new file named index.html
- Add the following HTML code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>React Events Handlers</title> </head> <body> <div role="main"></div> <script src="./events.js"></script> </body> </html>
- Save the file
Next, write a component defining an event handler for the onClick event:
- Create a new file named events.js.
- Import the React and ReactDOM libraries:
import * as React from 'react' import * as ReactDOM from 'react-dom'
- Define a class component that will render a h1 React element and a button React element, which will trigger the onBtnClick method whenever it's clicked:
class App extends React.Component { constructor(props) { super(props) this.state = { title: 'Untitled', } this.onBtnClick = this.onBtnClick.bind(this) } onBtnClick() { this.setState({ title: 'Hello there!', }) } render() { return ( <section> <h1>{this.state.title}</h1> <button onClick={this.onBtnClick}> Click me to change the title </button> </section> ) } }
- Render the application:
ReactDOM.render( <App />, document.querySelector('[role="main"]'), )
- Save the file.