Paulund
2024-04-15 #ReactJS

ReactJS onClick Event on Child Components

In this article we're going to investigate how to handle the onClick event on a child component within ReactJS.

Let's say we have a parent component that renders a child component. We want to handle the onClick event on the child component and update the parent component's state.

Pure JavaScript

Doing this in pure JavaScript works by taking a component like a button and adding the onclick event to run a function.

function myFunction() {
  alert('Hello World!');
}

<button onclick="myFunction()">Click me</button>

VueJS

In VueJS, you can handle the click event on a child component by emitting an event from the child component and listening to it in the parent component.

Here's an example of a parent component that renders a child component:

<template>
  <div>
    <h1>Parent Component</h1>
    <p>Count: {{ count }}</p>
    <Button @click="handleChildClick" />
  </div>
</template>

<script>
import Button from './Button.vue';

export default {
  components: {
    Button,
  },
  data() {
    return {
      count: 0,
    };
  },
  methods: {
    handleChildClick() {
      this.count++;
    },
  },
};
</script>

And here's the child component:

<template>
  <button @click="$emit('click')">Click Me</button>
</template>

In this example, the ParentComponent renders the Button and listens to the click event emitted by the Button. When the button in the Button component is clicked, the handleChildClick method in the ParentComponent is called, which updates the count data property.

ReactJS

In ReactJS, you can handle the onClick event on a child component by passing a function as a prop from the parent component to the child component.

Here's an example of a parent component that renders a child component:

import React, { useState } from 'react';

const ParentComponent = () => {
  const [count, setCount] = useState(0);

  const handleChildClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h1>Parent Component</h1>
      <p>Count: {count}</p>
      <Button onClick={handleChildClick} />
    </div>
  );
};

And here's the child component:

import React from 'react';

const Button = ({ onClick }) => {
  return (
    <button onClick={onClick}>Click Me</button>
  );
};

In this example, the ParentComponent renders the Button and passes a handleChildClick function as a prop. The Button has a button that triggers the onClick event when clicked.

When the button is clicked, the handleChildClick function is called, which updates the count state in the ParentComponent.

That's it! You've learned how to handle the onClick event on a child component in ReactJS.

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

Get 50% off forever using the code 50OFFUP.