skip to Main Content

I know how to pass data from parent component to child component but how can i pass data to an independent component ?

for example suppose to we have a component with this name : Test in Test component we have a value how we can pass this value to another component without i include it on first component ?

i write simplified of my code here

import {useState} from 'react';

const Test = () => {
    const [x,setX] = useState(0);


    const handleClick = () => {

        setX(x+1);
  
        };
    console.log(x);

    return(
    <div><div  onClick={handleClick} ref={ref}></div></div>
    )
}
export default Test;

on above code i have a value his name is x , i write bellow two other component


const Exit = () => {


    return(
<div>
    <p>Exit sec</p>
    <Score />
</div>)
}

export default Exit;

above component has a child component his name is Score and Exit component is header of site

const Score = () => {

   return(
    <div><p style={{color:"white"}}>YOUR SCORE IS {i want to put x value here} </p></div>
   )
}

export default Score;

please look at to above code i write in {} i want to put and show x value here . so how can i do this ?

finally i add these to index.js as bellow code

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Router>
    <Exit/>

    <Routes> 
      <Route path='/' element={<Test />} />  

    </Routes>
  </Router>
  </React.StrictMode>
);


2

Answers


  1. There are multiple ways to move data between independent components. These include creating react context or using global state management libraries such as redux. When I look at your situation, it seems that creating context is sufficient. I leave the documentation below on how to create the context.

    Documentation:https://react.dev/reference/react/useContext

    Login or Signup to reply.
  2. IF You want to share a data between multiple independent component in react js
    then you should below methods :

    1. React Context
    2. Redux
    3. State Management Libraries: Redux , MobX , Recoil
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search