0

I currently have a json file containing data for many people. It is in the following format:

    '1': {
        "name": Max
        "age": 8

    },

    '2':
        ....

Next, I want to display each of these people as links in my function Foo(). I have written the function below.

 import myData from './.../data.json'


 function Foo (){
    return (
        <div>
            <li>

                <Link to={`${url}/1`>{myData[1].name}</Link>}

            </li>
        </div>
    );
}

So far, I have done this manually. Now, what I want to do is somehow create a loop and create links for all of the people. I'm thinking of using 'map()' and 'Object.entries()' but I'm unsure of how and where to place them. Should I create a new function for them? I'm not sure....

1
  • Is this json structure something you control? If so you should convert this to an array of objects instead of an object of objects with numbers as keys. You could then just map through the array and display the items. Commented Feb 2, 2020 at 0:05

1 Answer 1

2

You can achieve this by calling Object.keys on myData and map the keys to links.

import myData from './.../data.json'


function Foo (){
  return (
    <div>
        <li>
          {Object.keys(myData).map(key => <Link to={`${url}/1` key={key}>{myData[key].name}</Link>)}
        </li>
    </div>
);

This will loop over all the keys ("1", "2", etc...). You can get the actual item with myData[key]. Don't forget to set the key property on the Link. This will help react to limit the number of needed DOM operations, if you later decide that this data is dynamic.

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

4 Comments

Awesome. So that works. How would I add a line break between each name?
No need for Object keys, just complicates it, instead use Object.values() and then <Link to={`${url}/1`>{obj.name}</Link>}
@EugenSunic beaware that Object.values is not supported in IE11, also don't forget to set the key attribute on the Link - for this the object-key might be the better fit.
@DarrelGulseth you might go trough an introduction trough HTML/CSS as is more of a presentation concern. By default a list items render next to each other. You can for example set display: block with CSS to the li to make it render vertically.

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.