Can I pass a 'const' variable from one component to another in ReactJS?

Viewed 2391

Say that I have a component (let's call it Comp1) where there is a 'const' variable that holds data.

I would like to pass that 'const' variable from Comp1 to my second Component, Comp2.

Is there a simple way to do such a thing ?

3 Answers

Yes, there's no problem passing const variable type to another component. The variable type only affects the behavior of the variable only.

Just pass the variable you desire to the component and accessing it through the target component props.

You can pass it as a props

function Comp1() {
  const comp1Data = "hello";
  return <Comp2 comp1Data={comp1Data} />;
}

function Comp2({ comp1Data }) {
  return comp1Data;
}

Certainly. You can pass any kind of data to other components.

Suppousing that Comp1 is the parent and Comp2 is the child element, you can take look at this example to see how it works:

const Comp1 = () => {
    const numbers = [1, 2, 3]
    return <div>
        <Comp2 nums = {numbers}/>
    </div>
}

const Comp2 = ({ nums }) => {
    console.log(nums)
    return <div>
        Numbers: {nums.toString()}
    </div>
}
Related