Home >>ReactJS Tutorial >ReactJS Events

ReactJS Events

ReactJS Events

This is a simple example, where only one component will be used. We just add onClick event that will trigger updateState feature once you click on the button.

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Data One...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState() {
      this.setState({data: 'Data Two...'})
   }
   render() {
      return (
         <div>
            <button onClick = {this.updateState}>Click me</button>
            <h4>{this.state.data}</h4>
         </div>
      );
   }
}
export default App;


main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

This above code will produce the following result.

Output

reactjs Events

Child Events

If we need to update the parent component state from child, we can create an event handler (updateState) in the parent component and transfer it to the child component as a prop (updateStateProp) where we can simply call it.

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState() {
      this.setState({data: 'From the child component data has been updated...'})
   }
   render() {
      return (
         <div>
            <Content myDataProp = {this.state.data} 
               updateStateProp = {this.updateState}></Content>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <button onClick = {this.props.updateStateProp}>Click me</button>
            <h3>{this.props.myDataProp}</h3>
         </div>
      );
   }
}
export default App;


main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

This above code will produce the following result.

Output

reactjs Events