React Data Pass Between Siblings

In React, passing values from one sibling component to another can be achieved by lifting the state up to a common ancestor:

Full Structure Image

Parent Component: 
  • In the parent component assign a variable "sharedValue". which changes the state by the Sibling1 component.
  • myCustomEvent and sharedValue are both custom events here.
  • myCustomEvent passing a method (fnValueChange). which receive new value and sets a common sharedValue state.
  • Finally, pass the changes a sharedValue to the Sibling 2 component.

Sibling 1 Component:
  • Receiving myCustomEvent method.
  • Set the new value for myCustomEvent by the onClick event of a button.
So this way shared variable's value is changed in the Parent component.


Sibling 2 Component:
  • Receive the shared variable as a parameter.
  • Bind with a <p> tag.


Output in Browser:




Code 👇

ParentComponent.js
import React, { useState } from 'react';
import Sibling1Component from './Sibling1Component';
import Sibling2Component from './Sibling2Component';

function ParentComponent() {
    const [sharedValue, setSharedValue] = useState('');

    const fnValueChange = (newValue) => {
        setSharedValue(newValue);
    }

  return (
    <div className='container card'>
        <Sibling1Component myCustomEvent={fnValueChange}/>
        <Sibling2Component sharedValue={sharedValue}/>
    </div>
  )
}

export default ParentComponent


Sibling1Component.js
import React from 'react'

function Sibling1Component({myCustomEvent}) {
   const myValue = 100;
    const funValueChangeCom1 = (e) => {
        const newValue = myValue;
        myCustomEvent(newValue);
   }
    return(
        <>
            <label>Input item in Sibling 1</label>
            <button className='btn btn-primary'
                onClick={funValueChangeCom1}>
                    Pass Value
            </button>
        </>
       
    )
   
}

export default Sibling1Component


Sibling2Component.js
import React from 'react'

function Sibling2Component({sharedValue}) {
  return (
    <p> Value in Sibling 2 : {sharedValue} </p>
  )
}

export default Sibling2Component

Post a Comment

0 Comments