Home > OS >  React.js passing one components variables to another component and vice-versa
React.js passing one components variables to another component and vice-versa

Time:12-14

I've just started to learn react. If I have a component with two variables, what is the easiest way to access these in another component? Use props, useState, useContext? How would you do to use the two variables inside ComponentTwo.

import React from 'react';

ComponentOne = () => {

varOne = Mike;
varTwo = Tyson;

Return(
<div>
</div>
)}

export default ComponentOne

import React from 'react';
import ComponentOne from '../OtherFolder/';

ComponentTwo = () => {

Return(
<div>
<p>{varOne}, {varTwo}</p>
</div>
)}

export default ComponentTwo```


CodePudding user response:

There are three different communication b/w components based on their relation.

  1. Passing data from Parent-to-child

For passing data from parent to child component, we use props. Props data is sent by the parent component and cannot be changed by the child component as they are read-only.

  1. Passing data from Child-to-parent

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component. The child component calls the parent callback function using props and passes the data to the parent component.

  1. Passing data b/w Siblings

For passing data among siblings, there are multiple methods we can choose from as shown below:

  • Combination of the above two methods (callback and use of props).
  • Using Redux.
  • ContextAPI

#Copied from this link. You should check the given link and go through that how to pass when we have such relationship b/w components and when to use what.

CodePudding user response:

It depends on your app's style. If it is a simple app where component two needs to access componenet one's variables props would be easy to use. However, as apps scale, you need to consider situations where component two needs to access a global state. Then, things change. Suppose your ComponentOne is the parent that contains & controls the state and ComponentTwo is the child and will only use the state passed from the parent.

Component1.js

import React from 'react';
import ComponentTwo from "./yourcomponent2directory.js"

const ComponentOne = () => {

varOne = Mike;
varTwo = Tyson;

return
(
<div>
<ComponentTwo varOne={varOne} varTwo={varTwo}/>
</div>
)}

export default ComponentOne

ComponentTwo.js

import React from 'react';
import ComponentOne from '../OtherFolder/';

const ComponentTwo = (props) => {

return(
<div>
<p>{props.varOne}, {props.varTwo}</p>
</div>
)}

export default ComponentTwo

or you can destructure props like...

const ComponentTwo = ({varOne,varTwo}) => {

return(
<div>
<p>{varOne}, {varTwo}</p>
</div>
)}

export default ComponentTwo
  • Related