Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to from one component set state another component in react native?

I have a problem. I want to set state another component from one component but I don't know how to do it?

like image 692
Kris Avatar asked Oct 08 '17 10:10

Kris


People also ask

How do you pass a set state from one component to another?

You can't directly call setState on a parent component from a child component because the updating of a component state is restricted to the current component. To handle this, simply pass a function from the parent to the child that contains setState .

How do you access the state of another component React?

To pass the state into another component, you can pass it as a prop. Then, inside <ExampleComponent /> , you can access the data as this. props.

How do you get a state from another component to React hooks?

React Hooks are a great way to add stateful logic into function components. So, if you want to maintain a state in the component you can do it using useState hook like so. As you can tell, the useState hook returns two values: the current state (i.e. the count variable) and a function that updates it (i.e. setCount ).

How do you set a state in components?

Syntax: We can use setState() to change the state of the component directly as well as through an arrow function. Example 1: Updating single attribute. We set up our initial state value inside constructor function and create another function updateState() for updating the state.


1 Answers

Component1: The component that you want to change the state from that.
Component2: The component that you want to change its state from another component.

  • If the the Component2 is child of the Component1, you can do this by passing new state as props to Component2.
  • If the Component2 is the parent of Component1, you should do this by a function that is defined in the Component2 (this function change the state of Component2) and passed to Component1 as a prop.
  • Otherwise you can use redux to manage the state and define a mapStateToProps function in Component2 to affect it by changing the state by Component1.
like image 72
Vahid Boreiri Avatar answered Oct 25 '22 21:10

Vahid Boreiri