0

I have this objects inside objects that I wanted to iterate in react

const [PersonInfo, setPersonInfo] = useState({
 {name: "Juan", address: "Street1"},
 {name: "Kristine", address: "Street2"}
}

I tried to render it in react using

return (
  <div>
    {{Object.keys(PersonInfo).map(key => 
        <option value={key}>{PersonInfo[key]}</option>
      )}
  </div>
)

But it only shows the first value which is Juan. What is wrong with my code?

3
  • 1
    The first snippet has incorrect syntax. Commented Dec 16, 2020 at 9:24
  • the data you pass to useState is not valid, and the code will not run. Please show some working sample. Commented Dec 16, 2020 at 9:28
  • @GabrielePetrioli default value in useState is {}. and I add new object using setPersonInfo({...PersonInfo, name: "Juan", address: "street1", }) Commented Dec 16, 2020 at 9:42

1 Answer 1

1

You have syntax errors, what you should do instead is save array insde your useState and loop over it using .map

const [personsInfo, setPersonsInfo] = useState([
  {name: "Juan", address: "Street1"},
  {name: "Kristine", address: "Street2"}
])

After that you can render it like so:

  return (
    <select name="personAddress">
      {personsInfo.map(person => {
        return (
          <option key={person.name} value={person.address}>{person.name}</option>
         )
      })}
    </select>
  );

This example assumes that each person has a unique name. Therefore the key={person.name}.

Sign up to request clarification or add additional context in comments.

Comments

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.