How to do it...

Firstly, create an index.html file where the React application will be rendered:

  1. Create a new file named index.html
  2. 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> 
  1. Save the file

Next, write a component defining an event handler for the onClick event:

  1. Create a new file named events.js.
  2. Import the React and ReactDOM libraries:
      import * as React from 'react' 
      import * as ReactDOM from 'react-dom' 
  1. 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> 
              ) 
          } 
      } 
  1. Render the application:
      ReactDOM.render( 
          <App />, 
          document.querySelector('[role="main"]'), 
      ) 
  1. Save the file.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.94.79