datogio
datogio

Reputation: 351

Access variable in child component that is defined in parent component

I want to access someVariable, defined in Parent function, in Child function.

import React from "react";

export default function Parent(props) {
    // Variable is definded
    const someVariable = false;

    return <div className="parentClass">{props.children}</div>;
}

Parent.Child = function(props) {
    // Want to access someVariable defined in parent function
    return someVariable && <div className="childClass">Should render if someVariable is true</div>;
}

// Use like this later
<Parent>
    // This will be rendered only if someVariable is true
    <Parent.Child />
</Parent>

Upvotes: 0

Views: 1146

Answers (1)

Phobos
Phobos

Reputation: 1646

You can pass your variable in the parent component as a prop to the child component:

const ChildComponent = (props) => {

    return (
       <View><Text>{props.someVariable}</Text></View>
    )
}

const ParentComponent = () => {
   const someVariable = false;

   return (
      <ChildComponent someVariable={someVariable} />
   )
}

Upvotes: 2

Related Questions