Hazem
Hazem

Reputation: 141

React Hooks useState array rendering two times

I need to upload images to my useState by using a function and after that I want to render this images the problem is I do not know how to render my returned array here is the code Code:

  const [logoImg, logoUpdater] = useState();
  const [title, updateTitle] = useState();
  const [carouselImages, carouselImagesUpdater] = useState([]);
  useEffect(
    (e) => {
      if (carouselImages.length > 0) {
      }
    },
    [carouselImages]
  );

  const carouselUploader = (file) => {
    var addedFile = file.target.files[0];
    carouselImagesUpdater((carouselImages) => [...carouselImages, addedFile]);
  };
  const titleFunction = () => {
    Preview(title);
  };
  return (
    <div>

      <div>
        <p>Upload Carousel images</p>
        <input
          type="file"
          accept="image/*"
          multiple
          onChange={(e) => carouselUploader(e)}
        ></input>
        {carouselImages.map((img) => (
          <img src={img} key="s"></img>
        ))}

Upvotes: 1

Views: 559

Answers (1)

HMR
HMR

Reputation: 39320

Re rendering multiple times is not what shows you broken images for your selected files. Here is an example of how you can set the file:

const App = () => {
  const [
    carouselImages,
    carouselImagesUpdater,
  ] = React.useState([]);
  const carouselUploader = (e) => {
    const reader = new FileReader();
    reader.addEventListener('load', (event) => {
      carouselImagesUpdater((carouselImages) => [
        ...carouselImages,
        event.target.result,
      ]);
    });
    reader.readAsDataURL(e.target.files[0]);
  };
  return (
    <div>
      <p>Upload Carousel images</p>
      <input
        type="file"
        accept="image/*"
        multiple
        onChange={(e) => carouselUploader(e)}
      ></input>
      {carouselImages.map((img, index) => (
        <img key={index} src={img}></img>
      ))}
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>

Here is some documentation on how to read files.

Upvotes: 1

Related Questions