W
W
WarriorKodeK2018-06-03 19:26:14
JavaScript
WarriorKodeK, 2018-06-03 19:26:14

How to attach an image to an element?

Hello. I receive data (objects) from api. Each object has elements with a name.
I need to attach a picture with this name. How to do it better?
Now I have this, but since the name is a string, it does not read. How can this problem be solved?

import React from "react";
import { Container, Row, Col } from "reactstrap";
import "./ProductList.css";

//Images
import Cappuccino from "../../images/Cappuccino.png";
import Americano from "../../images/Americano.png";
import Espresso from "../../images/Espresso.png";
import Lungo from "../../images/Lungo.png";
import Ristretto from "../../images/Ristretto.png";
import Doppio from "../../images/Doppio.png";

export const ProductsList = ({ productInformation }) => {
  return (
    <Container>
      <Row>
        {productInformation.data.map((element, index) => {
          return (
            <Col xs="3" className="coffee" key={index}>
              <img src={element.name} alt={element.name} />
            </Col>
          );
        })}
      </Row>
    </Container>
  );
};

I've tried that too, but it doesn't work either
<img
                src={`../../images/${element.name}.png`}
                alt={element.name}
              />

Project structure:
5b1416a593bd9989919899.png
Thank you all!

UPDATE:

I did it, but I feel like I did this shit))
<img src={require(`../../images/${element.name}.png`)} alt={element.name}/>

I'm waiting for your suggestions)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yura Komarov, 2018-06-03
@Yurajun

Look at the directory structure at the output of the collector (those in the dist folder) and write the path relative to it

dist
..images/
..js/
index.html

then the path will be ./images/name_pageeither../images/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question