Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement