0

I have a component in reactjs with all image imported as

import client01 from '../../assets/images/site/client-01.png';
import client02 from '../../assets/images/site/client-02.png';
import client03 from '../../assets/images/site/client-03.png';
import client04 from '../../assets/images/site/client-04.jpg';
import client05 from '../../assets/images/site/client-05.jpg';
import client06 from '../../assets/images/site/client-06.jpg';

and used in code as

<img src={client05} alt="client_5" />

My question is if I'm getting these values from an api, then how should I load the images. for example,

{
  "web-data": {
    "Asset": {
      "client01": "../../assets/images/site/client-01.png",
      "client02": "../../assets/images/site/client-02.png",
      "client03": "../../assets/images/site/client-03.png",
      "client04": "../../assets/images/site/client-04.png",
      "client05": "../../assets/images/site/client-05.png"
    }
  }
}

and i got these values and stored it in a local state, How to import these images in my reactjs component?

1
  • You can pass in the source like web-data.asset.client05 it will give the same output. As long as the field has a valid url it is ok. It doesn't matter it is variable or hard code string Commented May 6, 2020 at 13:34

2 Answers 2

1

you can use require method instead import


    <img src={require(web-data.Assets.client05)} alt="client_5" />
Sign up to request clarification or add additional context in comments.

Comments

1

You can fetch those when you load the component and save them in component state. Inbetween you can show a loader spinner to the user:


constructor(props) {
  super(props);
  this.state= {
    imagesLoaded: false,
    images: []
  }
}

componentDidMount() {
  fetch(APIURL)
    .then(data => {
      this.setState({ images: data.images, imagesLoaded: true });
    }
}

Then refer to those images in your component for example:

render() {
  if (!this.state.imagesLoaded){
    return <LoaderSpinner />
  }

  return (
    {
      for (img in this.state.images) {
        return <img src={img}/>
      } 
    }
  )
}

I tried to keep it generic. Hope I understood your question correct and this helps

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.