0

I created a React app using npx create-react-app and I've an image called image.jpg located at src -> images -> image.jpg. I want to display an image with every employee but having some problem with image(s). My code is running well but the image does not show up instead on saving and loading the application, the image doesn't display but broken icon is displayed with alt text. How can I solve this problem? Am I storing my image at wrong place or Is there some logical error in my code?

Here's what I tried:

import React from "react";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      term: "",
      names: [
        { name: "Deepak", job_profile: "Quality Analyst", description: "He is Passionate in Tester" },
        { name: "Deepinder", job_profile: "iOS Developer", description: "He is a Dedicated iOS Developer" }
      ],
      filteredData: [{}]
    };
  }

  render() {
    let terms = "";
    if (this.state.term) {
      terms = this.state.term.toLowerCase();
    }
    return (
      <div className="App">
        <label>Search Employee: </label>
        <input
          type="text"
          value={this.state.term}
          id="searchEmp"
          placeholder="Enter Name"
          onChange={(event) => {
            if (event.target.value.indexOf(" ") > -1) {
              alert("Please don\'t enter space.");
              this.setState({ term: "" });
              return;
            }
            this.setState({ term: event.target.value });
          }}
        />
        <br />
        <br />

        {this.state.names &&
          this.state.names
            .filter((x) => x.name.toLowerCase().startsWith(terms) || (x.description.toLowerCase().includes(terms)))
            .map((item) => {
              return (
                <div className="data-body">
                  <div>Name : {item.name}</div>
                  <div>Job Profile : {item.job_profile}</div>
                  <div>Description : {item.description}</div>
                  <div><img src={require('../src/images/image.jpg')} alt="profile_picture" /></div>
                  <input type="button" id="button" 
                  value="Delete" onClick={() => {
                  this.setState
                  ({ names: this.state.names.filter
                  (i => i.name !== item.name) });
                  }}/>
                  <div>{<br></br>}</div>
                </div>
              );
            })}
          </div>
          );
        }
}
export default App;

Output:

  • have you tried to use the import method to import the image as a variable and pass it to the src – Andre Sampaio Mar 02 '21 at 16:07
  • Does this answer your question? [How to import image (.svg, .png ) in a React Component](https://stackoverflow.com/questions/43823289/how-to-import-image-svg-png-in-a-react-component) – Lakshya Thakur Mar 02 '21 at 16:07
  • @LakshyaThakur-i've to strictly use `required` to get an image loaded on screen whereas in the given suggestion nothing is like that. –  Mar 02 '21 at 16:12
  • @AndreSampaio-as a new to React what I know is that 'import' method is used when we don't use 'required' in our ''. As I want to get image using 'required' that's why I didn't use 'import' method. I might be wrong for not using 'import' method with 'required' because I'm new to this. –  Mar 02 '21 at 16:22

3 Answers3

0

Try this,

   import React from "react";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          term: "",
          names: [
            { name: "Deepak", job_profile: "Quality Analyst", description: "He is Passionate in Tester" },
            { name: "Deepinder", job_profile: "iOS Developer", description: "He is a Dedicated iOS Developer" }
          ],
          filteredData: [{}]
        };
      }
    
      render() {
        let terms = "";
        if (this.state.term) {
          terms = this.state.term.toLowerCase();
        }
        return (
          <div className="App">
            <label>Search Employee: </label>
            <input
              type="text"
              value={this.state.term}
              id="searchEmp"
              placeholder="Enter Name"
              onChange={(event) => {
                if (event.target.value.indexOf(" ") > -1) {
                  alert("Please don\'t enter space.");
                  this.setState({ term: "" });
                  return;
                }
                this.setState({ term: event.target.value });
              }}
            />
            <br />
            <br />
    
            {this.state.names &&
              this.state.names
                .filter((x) => x.name.toLowerCase().startsWith(terms) || (x.description.toLowerCase().includes(terms)))
                .map((item) => {
                  return (
                    <div className="data-body">
                      <div>Name : {item.name}</div>
                      <div>Job Profile : {item.job_profile}</div>
                      <div>Description : {item.description}</div>
                      <div><img src={require("./images/image.jpg")} alt="profile_picture" /></div>
                      <input type="button" id="button" 
                      value="Delete" onClick={() => {
                      this.setState
                      ({ names: this.state.names.filter
                      (i => i.name !== item.name) });
                      }}/>
                      <div>{<br></br>}</div>
                    </div>
                  );
                })}
              </div>
              );
            }
    }
    export default App;
w0lf
  • 353
  • 3
  • 10
  • @w0lf-thanks for the help but this not what I'm looking for is. Do assist me by using `required` if you can or can I use `required` just after `src={` in the code you provided to get my desired result. Will it work or throw an error? –  Mar 02 '21 at 16:48
  • @soloLearner do you corrected `profile_picture` this line too? – w0lf Mar 02 '21 at 16:53
  • @soloLearner so, you are asking about requrie method, you can use `const myImage = require("../src/images/image.jpg");` to import image. then `profile_picture` to show image. – w0lf Mar 02 '21 at 16:55
  • @w0lf-i understand that I can display images using this code and I'd been done this. The thing I'm getting confused with is that how to do the same with using `required` in 'img' tag. I hope I'm clear with what I said. –  Mar 02 '21 at 16:59
  • @soloLearner you can find answer to your question here. https://stackoverflow.com/questions/39999367/how-do-i-reference-a-local-image-in-react – w0lf Mar 02 '21 at 17:03
  • @w0lf-okay if this is one of the way to get this done by storing image's path in a variable and so on. Then please make the required changes in the code I shared in my question. I'm new to react and really don't know of putting variables in a react app. I hope you won't mind for doing this. Many thanks in advance. –  Mar 02 '21 at 17:07
  • @soloLearner I can't understand, what method do you need ? import or require – w0lf Mar 02 '21 at 17:13
  • @soloLearner Also you have another problem, if you are working on `App.js` then use `import myImage from "./images/image.jpg"`; – w0lf Mar 02 '21 at 17:16
  • Also you can use, `profile_picture` – w0lf Mar 02 '21 at 17:18
  • @w0lf-my mean is not to bother you. But I'm new to React and what I know is that when we use `require` then we don't use `import`. am I right? If yes then I want to use `require` that's why I didn't use `import` in my code. I might be wrong for not using `import` with `require` because I'm learning. Apart, I want to get done my task using `require`. –  Mar 02 '21 at 17:24
  • @soloLearner I've edited my answer, you can try it. Actually the error is not the importing the image. The error is you are requiring image in wrong place. Always put images and other resources inside the `src` folder. – w0lf Mar 02 '21 at 17:31
0

just created the app using your code it worked just check this

<img src={require("./images/logo.png")}  alt="profile_picture" />

my folder structure is like

├── public
├── src
│   ├── images
│   │        ├── logo.png
│   │
│   ├── index.js
  

also If the images are inside the src/assets folder you can use require with the correct path in the require statement, and it also worked for me

const userImage = require('./images/logo.png');

<img src={userImage}  alt="profile_picture" />

this approch also worked

import userImage from'./logo.png';
0

This is the stupidest thing but after hours of testing both on localhost and the hosted build on AWS Amplify. But I was using a .jpeg file and I re-exported the photo as a png and it solved. my issue.

Now I am pulling the image in through 2 different ways:

import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
// import Image from 'react-bootstrap/Image'

import '../css/about.css';
import profilePicture from '../images/profile-picture.png'
import { BsCode } from "react-icons/bs";


const About = () => {

  return (
    <Row className='section'>
      <Col id="about" xs={11} sm={11} md={9} xl={7}>
        <Row id="about-row">
          <Col xs={12} md={8}>
            <h3 id='about-description'>I am an engineer who's passion for many art forms has led me to create visually influenced web applications. These often manifest themselves through data-driven analytics and intuitive graphics.</h3>
            <h6 id='about-technical'>main techincal interests</h6>
            <div id='about-skills'>
              <span><BsCode className='about-skills-icon'/>Python</span>
              <span><BsCode className='about-skills-icon'/>React</span>
              <span><BsCode className='about-skills-icon'/>Javascript</span>
              <span><BsCode className='about-skills-icon'/>NodeJS</span>
              <span><BsCode className='about-skills-icon'/>R</span>
              <span><BsCode className='about-skills-icon'/>Git</span>
            </div>
            <p id='about-resume'>for more skills, checkout out my <a id='about-resume-link' href='https://drive.google.com/file/d/1UFBZjwpirNNVCuxiPMb0rGs2dQqCP0RE/view?usp=sharing'>resume</a></p>
          </Col>
          <Col xs={6}  md={4}>
            {/* image found in the ./src/images/<filename>.png */}
            <img id='about-profile' src={profilePicture} alt='about-profile'/>
            {/* image found in the ./public/images/<filename>.png */}
            <img id='about-profile' src='./images/profile-picture.png' alt='about-profile'/>
          </Col>
        </Row>
      </Col>
    </Row>
  )
}

export default About