简体   繁体   中英

React - how to set inline CSS for each element of map function?

I have an application in React where I'm trying to read in data from a JSON file. The JSON file is in the following format:

[
    {
        "name": "Max",
        "age": "21",
    },

    {
        "name": "Sam",
        "age": "18",
    }

    ........
]

I have successfully read in the right data and displayed it on my screen, like this:

function foo(){
    const styling = css`
        font-size: 30px;
    `;

    return(
        <div>
            {people.map((person, i) => <Format key={i} {...person} css={styling}/>)}
        </div>
    );
}

Although all the information correctly displays on the screen, the styling is not getting applied to each person. How could I change this?

EDIT

Format component:

function Format({name, age}){
   return (
      <div>
         <h1>{name}</h1>
         <h2>{age}</h2>
      </div>
   );
}
function Format({name, age, css}){
   return (
      <div css={css}>
         <h1>{name}</h1>
         <h2>{age}</h2>
      </div>
   );
}

you passed styled to your component but you didnt use them in your child component

and plus using idx as key is not the best practice. following article explains why. https://reactjs.org/docs/lists-and-keys.html

if name is unique you can pass each items name to mapped children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM