How do I export a variable name (not the full component) from one component to another in React?

Viewed 38

I'm finding it hard to export or pass the variable with the names objHead and objDetails from this component to another component so that I can use it there.

is there like a keyword I can use in react for it just like the way module.exports is in Nodejs?

function Add(prop){
//function to store the detail and title prop into an object

const AddCart = () => {
       
          const obj = {
                        head:prop.title,
                        body:prop.details
                    }

            const objHead = obj.head;
            const objDetails = obj.body;
    
          

}
    
    return(
        <div>
            <div className="box">
                <h5 id="AddHead">Add header</h5>
                <p>{prop.title}</p>
                <p>{prop.details}</p>
             </div>
             <button className="btn" onClick={AddCart}>Add to cart</button>

             <hr></hr>
        </div>
    )
}

export default Add;
1 Answers

Well there are multiple ways to pass a variable from one component to another one , depending on the position of your target components.

-In Case Target Component is Child: If your target component is being rendered inside the component from where you want to pass variable, then pass it using props.

-In Case Target Component is Parent: In this case you will store the variable in a state suing usestate hook in parent component, and pass the setter of the state to child component as prop.

Related