2021年6月20日 星期日

[image, react, component] How to add an image to the React component

How to add static asset to the React component

井民全, Jing, mqjing@gmail.com

Github


1. Quick

// Bundle

import redlight from './res/redlight.svg'


// Usage

<img src={redlight}></img>


Tree


├── package.json

├── public

├── README.md

├── src

│   ├── App.css

│   ├── App.test.tsx

│   ├── App.tsx

│   ├── component

│   │   ├── my-image.tsx

│   │   └── res

│   │       ├── greenlight.jpeg

│   │       └── redlight.svg

│   ├── index.css

│   ├── index.tsx

│   ├── logo.svg

│   ├── react-app-env.d.ts

│   ├── reportWebVitals.ts

│   └── setupTests.ts

├── tsconfig.json

└── yarn.lock


2. Code

2.1. Simple

2.1.1. Component Part

File: ./src/component/my-image.tsx

import React from 'react';

import redlight from './res/redlight.svg'    // Bundle


class MyImage extends React.Component { 

    render() {

      return (

        <div>

                   <img src={redlight}></img>     // Usage

        </div>

      );

    }

}


export default MyImage;


2.1.2. App.tsx Part

import React, { useState } from 'react';

import logo from './logo.svg';

import './App.css';

import MyImage from './component/my-image';


function App() {


  return (

    <div className="App">

      <header className="App-header">

        <p>

          <MyImage /> 

        </p>

      </header>

    </div>

  );

}


export default App;


3. Install & Test

yarn install && yarn start


4. Result



5. Makeclean 

# run clean up

yarn clean

 

The clean script

File:./package.json     

"clean": "(rm -fr node_modules; rm -fr build; find . -name \"*.js\" -type f|xargs rm -f; find . -name \"*.map\" -type f|xargs rm -f)"


6. Reference

  1. https://create-react-app.dev/docs/adding-images-fonts-and-files/


7. Further Info

  1. How to create a React component