Boris
Boris

Reputation: 113

how can i get a value from a child component to parent screen in react native?

hi i am new to react native... my problem is, how can we catch a value set in child-component from the parent screen? here is a sample code (the parent and child are in different source_files).. how can i read the value in variable count from the ParentScreen? when the Count++ button is clicked in the child-control, the txtFromChild variable needs to be updated.. how can we do it?

ParentScreen.js

const ParentScreen= () => {     
    const [txtFromChild, setTextFromChild ) = useState('');         

    return (
        <View>
        <Text>{txtFromChild}</Text>
        <ChildControl />
        </View>    
    );    
};    
export default ParentScreen;

and this is the child control in seperate file

ChildControl.js
    const ChildControl= () => {     
    const [count, setCount ) = useState(0);       

    return (
        <View>
        <Button title="Count++" onPress={()=>{setCount(count+1)}}/>
        </View>    
    );    
};    
export default ChildControl;

Upvotes: 1

Views: 3313

Answers (1)

Manojkanth
Manojkanth

Reputation: 1169

ParentScreen.js

There are multiple way to get the value. Most simple way is Just get that value from a function. Just try this code, You will get that count in your parent view once you click that button in you child view.

const ParentScreen = () => {
  const [txtFromChild, setTextFromChild] = useState("");

  const getCountValue = (yourvalue) => {
    console.log(yourvalue);
  };
  return (
    <View>
      <Text>{txtFromChild}</Text>
      <ChildControl getCountValue={(value) => getCountValue(value)} />
    </View>
  );
};
export default ParentScreen;

ChildControl.js

  const ChildControl = (getCountValue) => {
  const [count, setCount] = useState(0);

  const onPressButton = async () => {
    await setCount(count + 1);
    getCountValue(count);
  };
  return (
    <View>
      <Button title="Count++" onPress={() => onPressButton()} />
    </View>
  );
};
export default ChildControl;

Upvotes: 3

Related Questions