Tag Archives: Interaction in React

COMPONENT INTERACTION IN REACT

Component Interaction in React

Component Interaction in React

In React JS, there is often a need to pass data from one component to another. If you are passing data from somewhere in a component, to somewhere else inside the same component, this can be done through the state. So, let’s dive deep in and know more about component interaction in React.

WHAT IS THE STATE?

The heart of every React component is its “state”, an object that defines how that component renders and performs. In other words, “state” is what allows the user to create components that are dynamic and interactive.

Assume of the state as the difference between water, ice, and vapor. It is the same object, but subject on conditions, it can behave differently. That’s the same way to use state within components. The user can change the way objects appear, or interact by changing the state of those objects within a component.

HOW TO CHANGE STATE IN A COMPONENT?
Generally, the user would need to declare the state after setting the constructor.
class component_A extends Component {
constructor() {
super();
this.state = {
data: [],
};
}

In this case, we are outlining the state of data. We have defined it here as an empty array. We have to use an empty object, or empty quotes, depending on the data type we wanted to change the state of. Then when we are ready to change the state, we would simply use “this.setState.” With our instance above, it might look like this:

this.setState({data: data});

Here the user has two components, and the user needs to pass the data from one component to an other. The user would not be able to use state. The state can only be transferred within the component where it was created. Instead, the user can use props or properties.

Let’s say, the user has component_A, with files nested inside of it, and then it’s child components, component_B, and component_C. It is very probable that component_A would have data that the user would need to access in component_C. How can the user access that, or pass the data from component_A to component_C? Ultimately, what the user has to do, is;

If the user wants to pass the property of color from the parent component to one of the child components. The user can pass prop using “this” the same way set the state in a component earlier. In that instance, the state could then be used and passed throughout the component.

Passing data from parent to child components is little trickier, in that, the user cannot pass data in an unbroken chain to other components. In the above instance, the user actually needs to pass the data, in this case, {this.props.color} from component_A to component_B and then to component_C.