Search code examples
javascriptreactjsapiecmascript-6get

ES6 Attaching a url to a mapped object from an array


I'm working on a side project with React and I'm using the tmdb API.

My GET request

performSearch = () => { // Requesting data from API
    axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
        .then((res) => {
            console.log(res.data.results);
            this.setState({ searchResults: res.data.results});
        });
}

And I render the results with the map function like so

 const Suggestions = (props) => {
  const options = props.searchResults.map(r => (
    <li className='search-results'
      key={r.id} >
      {r.title}
      {r.name}
      {r.poster_path}
    </li>
  ))
  return <ul>{options}</ul>
}

export default Suggestions

What I need is this URL 'https://image.tmdb.org/t/p/w300' + {r.poster_path} to render out the image, how do I go about doing that? End result looks like this 'https://image.tmdb.org/t/p/w300/gwPSoYUHAKmdyVywgLpKKA4BjRr.jpg'


Solution

  • You can pass it as an attribute into an img-object. For example, using template strings:

     const Suggestions = (props) => {
       const options = props.searchResults.map((r) => (
         <li className='search-results' key={r.id}>
           {r.title}
           {r.name}
           <img src={`https://image.tmdb.org/t/p/w300/${r.poster_path}`} alt={r.title} />
         </li>
       ))
       return <ul>{options}</ul>
     };
    
     export default Suggestions