Search code examples
javascripthtmlnode.jsreactjs

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


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```



Solution

  • It depends on your app's style. If it is a simple app where component two needs to access component 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