1

I have watched dozens of youtube videos, but do not come across my problem.

In React, I want to show a picture from the spoonacular API of which I only get the "name.png" in the console (i.e. not the full url).

At setPicture(result.data.results[0].image) I get the name of the picture in the console and I just need to get the url in front of it. I tried this with the following <img src={`https://spoonacular.com/cdn/ingredients_250x250/${picture}`} alt="food">; and I also tried to put the url in the useState but that doesn't work.

My complete code is as follows:

    const [food, setFood] = useState([]);
    const [picture, setPicture] = useState([])

    useEffect(() => {
        async function fetchFood() {
            const result = await axios.get(`https://api.spoonacular.com/food/ingredients/search?query=rice&number=20&apiKey=${apiKey}`);
            console.log(result);
            console.log("DATA:", result.data);
            console.log("DATA RESULTS:", result.data.results);
            // console.log("DATA RESULTS[0]:", result.data.results[0]);
            // console.log("DATA RESULTS[0]:", result.data.results[0].title);
            setFood(result.data.results[0]);
            setPicture(result.data.results[0].image)
        }

        fetchFood();
    }, []);

    return (
        <div>
            <div>{food.name}</div>
            <img src={`https://spoonacular.com/cdn/ingredients_250x250/${picture}`} alt="food">;
        </div>
    );
}
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102

1 Answers1

2

JSX supposed to be closed with /> (or > if it's have children) not >;

<img src={`https://spoonacular.com/cdn/ingredients_250x250/${picture}`} alt="food" />

You can use >; if you only want to show one element, here's for example:

function app() {
  return <img />;
}

It will work because it is end of return. And you already have it.

return (
  <div>
    <div>{food.name}</div>
    <img src={`https://spoonacular.com/cdn/ingredients_250x250/${picture}`} alt="food" />
  </div>
); // here
nouvist
  • 1,107
  • 10
  • 24