Search code examples
reactjsslidercarousele-commerce

How to add image from local folder in the state of my react component?


here is the code and I want to add images from my local folders instead of item#1,2,3,... how can I do that? besides if anyone of you knows a good source code for creating product slider please let me know thank you.

import Carousel from 'react-elastic-carousel';

class ProductSlider extends Component {
  state = {
    items: [
      {id: 1, image: 'item #1'},
      {id: 2, image: 'item #2'},
      {id: 3, image: 'item #3'},
      {id: 4, image: 'item #4'},
      {id: 5, image: 'item #5'}
    ]
  }

  render () {
    const { items } = this.state;
    return (
      <Carousel>
        {items.map(item => <div key={item.id}>{item.image}</div>)}
      </Carousel>
    )
  }
}
export default ProductSlider;

Solution

  • if you are building app with create-react-app. one of the easiest way to import image is to use public folder. place your image into public and write your code like this.

    1. make public folder in your project's root path
    2. place your images into public folder
    public
    ├── 1.png
    ├── 2.png
    ├── 3.png
    └── 4.png
    
    import Carousel from 'react-elastic-carousel';
    
    class ProductSlider extends Component {
      state = {
        items: [
          {id: 1, image: '/1.png'},
          {id: 2, image: '/2.png'},
          {id: 3, image: '/3.png'},
          ...
        ]
      }
    
      render () {
        const { items } = this.state;
        return (
          <Carousel>
            {items.map(item => <div key={item.id}><img src={item.image} alt='fill something' /></div>)}
          </Carousel>
        )
      }
    }
    export default ProductSlider;
    

    you can find more about public folder from this document. https://create-react-app.dev/docs/using-the-public-folder/