简体   繁体   中英

How to import/add multiple images as per JSON key value in ReactJS?

i am trying to add multiple images as per the JSON key value from JSON data

{"name":"abbreviation"}-> {"Alabama": "AL", "Alaska": "AK", "Arizona": "AZ", "Arkansas": "AR", "California": "CA", "Colorado": "CO",...}

I have images downloaded and name like 'al.png' , 'ak.png' , 'az.png' which as per value of JSON format . How do I set each image for particular Card Component that I have created

    import  "./card.styles.css"

export const Card =(props)=>(
    <div className="card-container">
    <h1>{props.states.name}
       I am trying to add images here



     
 </h1></div>)"

This is how I am fetching all states name onto Card-list component-

componentDidMount() {
    fetch("https://worldpopulationreview.com/static/states/abbr-name-list.json").
    then((response) => response.json())
    .then(users=>this.setState({states:users}));

  }

  render() {
    return (
      <div className='App'>
      <CardList states={this.state.states}>
      </CardList>
        
      </div>```

if you have those images in public folder then your card components should like this:

export const Card =(props)=>(
  <div className="card-container">
  <h1>{props.states.name}
     <img src={`${process.env.PUBLIC_URL}/images/${props.states.abbreviation.toLowerCase()}.png`} />
  </h1>
</div>
)

From what I understand you want to give the individual cards their data?

If I am right, in your CardList component,

users.map((user) => <Card><h1>{user.name}</h1><img src={user.image}</img></Card>

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