NextJs / View / Passing Data or Event or Object between components
Data passing between components
-
STEPS
1. Pass from parent to child
Pass data as prop import React, { useState } from 'react'; const App = () => { const [object, setObject] = useState({ name: 'John Doe', age: 30, }); return ( import React, { useState } from 'react'; const MyComponent = ({ object }) => { console.log(object); // { name: 'John Doe', age: 30 } return ( The object is: {JSON.stringify(object)}); };2. Pass data from child to parent
1. Pass a function as a prop to the Child component.
2. Call the function in the Child component and pass the data as arguments.
3. Access the data in the function in the Parent.
import {useState} from 'react'; function Child({handleClick}) { return ( Count: {count}
1. when clicking on the button in the child, the function 'handleClick' is called.
2. the function 'handleClick' is defined in parent component3. Pass event from child to parent
import {useState} from 'react'; function Child({handleClick}) { return ( Count: {count}
4. Passing an object from the Child to the Parent component
import {useState} from 'react'; function Child({handleClick}) { const employee = { id: 1, name: 'Bobby Hadz', salary: 500, }; return ( Employee id: {employee.id}
Employee name: {employee.name}
Employee salary: {employee.salary}