Handling Events in React with a simple function

ยท

3 min read

In this article you will learn how to handle events in react. This is a pre-requisite to know how to manage react states.
We have a component called Car:

const Car = ({brand, year}) => {
  return(
    <>
      <p>The {brand} vehicle brand was first manufactured in the year {year}.</p>
    </>
  );
}
export default Car;

We also have a our root component App.js looking like this:

import './App.css';
import Car from "./Car/Car"

const App = () => {
  return (
    <div className="App">
      <h1>Hi, I'm a react App</h1>
      <p>This is really working!</p>
      <Car brand="Junsa" year="2019" />
    </div>
  ); 
}
export default App;

To demonstrate event handling we add some code in App.js .
๐ŸŒŸ Below the paragraph element add a button with an onClick event attribute
<button onClick={}>Switch Name</button>
๐ŸŒŸ We add a function to our App function component before returning, like this:

  const switchNameHandler = () => {
    console.log("Collide Air Strike");
  }

๐ŸŒŸ Then we should add the name switchNameHandler in between the onClick event attribute to look like this:
<button onClick={switchNameHandler}>Switch Name</button>
When you run your app and open the console in browser tools and click the button a message should be produced showing:

Collide Air Strike

The complete code of your App.js should look like this:

import './App.css';
import Car from "./Car/Car"

const App = () => {

  const switchNameHandler = () => {
    console.log("Collide Air Strike");
  }

  return (
    <div className="App">
      <h1>Hi, I'm a react App</h1>
      <p>This is really working!</p>
      <button onClick={switchNameHandler}>Switch Name</button>
      <Car brand="Junsa" year="2019" />
    </div>
  ); 
}
export default App;

Thankyou ๐Ÿ’ซ