Passing state throughout components in React

In a react application when you want to pass values from your child component to their parent component it is called “Lifting State Up”. This very easy concept always tend to leave me puzzled. Below is the very basic implementation of this, but the caveat is that we are not passing a value but understanding how it works.

Parent.js

import Child from "./Child";


export default function Parent() {
 const handleFunction = () =>
   console.log(
     "This triggers when property is called inside of child component"
   );


 return (
   <div>
     <Child property={handleFunction} />
   </div>
 );
}

Child.js

export default function Child({ property }) {
 const propertyAsFunction = () => {
   property(); // Calling this function will trigger the function held in the parent component
 };
 return (
   <div>
     <h2>Child Element</h2>
     <button onClick={propertyAsFunction}>
       This button will trigger the parent function
     </button>
   </div>
 );
}

When passing state or a value through components you will need a couple things.

  1. Property
  2. Function

When calling the <Child> component in the <Parent> component you need to include the property that you will be passing along.

// In the Parent.js
<Child propertyToPass = {handlefunction} />

The property propertyToPass is the property you will be passing and throwing back inside of your Child.js Child component.

// In Child.js
export default function Child(propertyToPass){

While in Child.js that property now acts as a function that will trigger what ever function is attached to the property in the parent component

// In Child .js
<button onClick={()=>propertyToPass()}> Child button </button>

// In Parent.js
<Child propertyToPass = {()=>console.log("Whatever function right here will trigger")}

So when we are wanting to pass a value from child to parent all we have to do is add the value as a parameter in the function in the Child component.

// In Child .js
const send = 'whatever you want to send'
<button onClick={()=>propertyToPass(sendValue)}> Child button </button>

// In Parent.js
<Child propertyToPass = {(receivedValue) =>console.log(receivedValue)}

You can change that send value to a string or an object as well. By following this you will be able to successfully “Lift State Up”


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *