0

I am new to React. I have a component that is meant to display a profile's data.

I am unsure as to how to pass that to the component. It seems to me the best way is to send it as an array. Eg:

const person = {
  name: 'Bill',
  age: 42,
  sex: 'male',
  occupation: 'driver',
};

And to output it somewhat like:

return (
  <Typography variant="h6">{person.name}</Typography>
  <Typography variant="body1">{person.age}</Typography>
  <Typography variant="body1">{person.sex}</Typography>
  <Typography variant="body1">{person.occupation}</Typography>
)

I'm just not sure how to do this and cannot find anything on Google or SO.

Would anyone be able point me in the right direction?

1
  • hm..."best way is to send it as an array."... sorry but where's the array? do you mean how to loop thought the object and render every key value pair with Typography? Commented May 12, 2020 at 3:38

1 Answer 1

1

You can pass your object as a prop to your child component:

import React from "react";

const person = {
  name: 'Bill',
  age: 42,
  sex: 'male',
  occupation: 'driver',
};

// in ParentComponent.js
<ChildComponent person={person} />


// in ChildComponent.js
const ChildComponent = ({ person }) => {
 return (
  <div> // or <React.Fragment>
   <Typography variant="h6">{person.name}</Typography>
   <Typography variant="body1">{person.age}</Typography>
   <Typography variant="body1">{person.sex}</Typography>
   <Typography variant="body1">{person.occupation}</Typography>
  </div>
 )
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I wasn't very clear. How to I get the props from where the component is called to where I can use them, as you have above
I updated my answer, I hope that answers your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.