How to add images in JSX in a component in React.js?

How to use Components in React.js?»

Inside Bootstrap class col-md-8, you’ve written the code to print news data. Inside col-md-4, you’ll add some images. You can either download some free images from the Internet, put it inside the public directory and use them in the code. Otherwise, you can use a library called faker.js to get some fake images easily.

To install the library / Node.js package, go to your terminal, stop the live React server (Ctrl + C) and run the following command:

npm install faker --save -g 

This –save flag means that you’re going to save the package in your local project. It’ll also create an entry for the package name inside your package.json file. For example, my package.json file now looks like this:

{
  "name": "components",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "faker": "^4.1.0",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

You’ll notice under “dependencies”, I have “faker” and it’s version number mentioned. This was done by faker.js library.

Once you’ve installed the library, run the server again with npm start.

Now, to use the library, you first need to import by the package name. The import statements of your index.js file should look like:

import React from 'react';
import ReactDOM from 'react-dom';
import faker from 'faker';

Inside col-md-4, you’ll be adding an image. So, add the following code:

<div className="col-md-4">
<img alt=”news” src={faker.image.city}/”
</div>

You’ll notice that while typing faker.image. , you’ll be shown multiple image options to choose from from the dropdown tooltip in your editor (for example, city, animals, avatar, business, cats, etc). These are the type of images that faker library supports. I’ve take a city image in my case by doing faker.image.city().

Leave a Comment