How to send values without navigating to child component

Viewed 28

good morning

I wanted to send some array data to child component , the purpose of this component is to make my code in one page shorter

this page i named it homepage, inside homepage there are multiple charts

import Chart01 from ../components/chart01
import Chart02 from ../components/chart02
import Chart03 from ../components/chart03

and in this homepage there will be buttons that (I'm planning to) send value to those 3 charts

const [FirstValue,setFirstValue] = useState(0)

return(
<View>
  <View>
     <Button onPress={()=>setFirstValue(1)}
     <Button onPress={()=>setFirstValue(2)}
     <Button onPress={()=>setFirstValue(3)}
  </View>
  <Chart01/>
  <Chart02/>
  <Chart03/>
</View>
)

How do i send the FirstValue from HomePage to Chart01 Chart02 Chart03 ?

and in Chart01, how do I call value that sent from HomePage ?

Thank you

2 Answers

In home you have pass like below,

<Chart01 value={FirstValue}/>
<Chart02 value={FirstValue}/>
<Chart03 value={FirstValue}/>

In Chart01,02,03 definition, you have to read props.

const Chart01 = (props) => {
  const { value } = props;
  // someting
};

Pass the values as props to the chart components.

const [firstValue, setFirstValue] = useState(0);


return(
  <View>
    <View>
      <Button onPress={() => setFirstValue(1)}
      <Button onPress={() => setFirstValue(2)}
      <Button onPress={() => setFirstValue(3)}
    </View>
    <Chart01 value={firstValue} />
    <Chart02 value={firstValue} />
    <Chart03 value={firstValue} />
  </View>
);

Within the chart components you can access the passed value from the value prop (or whatever you name it). For example:

props.value
Related