Pooria Han
Pooria Han

Reputation: 688

Emitting custom event in React

In Vue.js we can emit custom events along with a parameter like

this.$emit('bark', 3);

and then we can listen to this event on the parent component like

<parent-component @bark=handleBark />

handleBark (howManyTimes) {
    console.log(howManyTimes);
    // logs 3
}

How can we do that in React?

Upvotes: 38

Views: 45469

Answers (3)

A&#255;lo
A&#255;lo

Reputation: 311

You can also use this library, Evento, that I created to replicate Svelte's createEventDispatcher() and Vue's $emit.

You have to create the event emitter (named by convention evento) using the hook, and use the dispatcher as you would do with $emit by passing the name of the event and the payload :

const Dog = (props) => {
  const evento = useCreateEvento(props)
 
  return <button onCLick={() => evento('bark', 3)}>wof</button>
}

The parent Component will be able to listen to the Event as it would listen to a React Event: by using on + the capitalized name of the Component Event. The data will be stored in event.detail.

<Dog onBark={e => console.log(`barked ${e.detail} times`)} /> 
/* will log 'barked 3 times'*/

Upvotes: 8

Beginner
Beginner

Reputation: 9095

As @usafder, mentioned the way. I am just adding the basic callback function for an input field. So on the console you can see the current value.

Basically callback function is the way to get the data from the Child component.

Parent.js

import React from "react";
import Child from "./Child";

export default function App() {
  const parentHandleChange = (e) => {
    console.log(e.target.value);
  };

  return (
    <div>
      <Child handleChange={parentHandleChange} />
    </div>
  );
}

Child.js

import React from "react";

const Child = (props) => {
  return <input onChange={props.handleChange} />;
};

export default Child;

Working codesandbox

Addition to it if you need return a custom value use like this

<Child onHandleChange={() => parentHandleChange(10)}

Because in this it won't call every-time if you want pass a value.

Upvotes: 27

usafder
usafder

Reputation: 816

You just simply pass down the custom event handler as props.

For example if you have Parent and Child functional components. You can then define the custom event handler in the Parent component like:

function Parent(props) {
  const handleBark = (howManyTimes) => {
    console.log(howManyTimes);
  };
  
  // note below I am sending the handleBark method to Child as props
  return (<Child bark={handleBark} />);
}

and then inside the Child component you can simply call it as:

props.bark(10);

Upvotes: 14

Related Questions