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 ( ); } export default function Parent() { const [count, setCount] = useState(0); const handleClick = num => { // 👇️ take the parameter passed from the Child component setCount(current => current + num); console.log('argument from Child: ', num); }; 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 ( ); } export default function Parent() { const [count, setCount] = useState(0); const handleClick = (event, num) => { console.log(event.target); console.log('from Child: ', num); setCount(current => current + num); }; 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 ( ); } export default function Parent() { const [employee, setEmployee] = useState({ id: 0, name: '', salary: 0, }); const handleClick = obj => { // 👇️ take the parameter passed from the Child component setEmployee(emp => ({...emp, ...obj})); console.log('argument from Child: ', obj); }; return (); }Employee id: {employee.id}
Employee name: {employee.name}
Employee salary: {employee.salary}
MANVIA BLOG