I want to put the images in an object or array and use them when I need them. What should I do?

575 views Asked by At

I wish I could bring all the images to the 'Image.jsx' file and easily take them out of another file in React

For example

export const Header = ({ title, children }) => {
  return (
    <>
      <Title>{title}</Title>
      <Items>{children}</Items>
    </>
  );
};
Header.propTypes = {
  title: PropTypes.node,
  children: PropTypes.object,
}; 
// I made a separate component. And the codes in the component will be used in other files.

import { Header } from "../BaseLabel";
const FriendstHeader = () => {
  return (
    <>
      <FriendContainer>
        <Header title="친구" style={{ color: "#191919" }}/>
      </FriendContainer>
    </>
  );
};
export default FriendstHeader;

I want to manage the image. like the example. This is Image.jsx

import React from 'react';
import PropTypes from 'prop-types';
import Search from "images/search.png";

const imageSrc = [ Search ];
export const Image = (props: imageSrc) => {
  return (
   <>
     <img alt="">{imageSrc.Search}</img>
   </>
  );
};
Image.propTypes = {
  imageSrc: PropTypes.node,
};

This is the main screen that will bring up the image.

import React from 'react';
import Search from "images/search.png";

const Header = () => {
  return(
    <>
     <Items>
       <img src={Search} width="18px" height="18px" alt="" />
     </Items>
    </>
  )
}
export default Header;

In fact, the image is not one, but it has been reduced to one above not to look complicated.

1

There are 1 answers

0
Bayarjargal Jargalsaikhan On BEST ANSWER

Actually bundling images in code is bad idea. You should move your images or static files to public or public/images (it would make more sense).

Then your Image.jsx can be like this.

import React from 'react';

const Image = ({src, alt="", ...rest }) => {
    return <img src={src} alt={alt} {...rest}/>
}

export default Image;

After that you can use your Image component like this:

import React from 'react';

const Test = () => {
   return 
<div>
   <p>Hello world</p>       
   <Image src="/images/Search.png" width="20" height="20" style={{ marginBottom: 10 }} onClick={() => {}} alt="This is alt for search image"/>
</div>
}

export default Test;