Home > Mobile >  React: Check Array if string matches and set state
React: Check Array if string matches and set state

Time:12-08

I have the following Array:

[
    "/test/static/media/its9-odc_d.9d5de720.png",
    "/test/static/media/its9-odc_m.178c1879.png",
    "/test/static/media/its9-odc_w.5e70ca59.png",
    "/test/static/media/its9-odc_y.8cf41473.png"
]

When I click on a Button, either _d, _m, _w or _y is saved in a React state (timeperiods).

I need a function which should save the string which matches my timeperiods in another React state (imageSource), so I can render the image.

This is what I tried so far but I always get returned 'yay' and when I try to setImageSource I get an error for infinite loop.

  const imageForTimeperiod = () => {
    images.forEach((img) => {
      if (timeperiod && img.split('.')[0].includes(timeperiod)) {
        console.log('yay');
        // setImage(img);
      }
    })
  };

{Object.entries(Timeperiods.timeperiods).map((entries) => {
    return (
        <Button onClick={() => setTimeperiod(entries[1].file)}>
            {entries[0]}
        </Button>
    );
})}

In the end:

I click on Button 1 Day, it sets timeperiod to _d and I show the image /test/static/media/its9-odc_d.9d5de720.png.

CodePudding user response:

You can pass the name of timeperiod on clicked button and then based on the name set the image and timePeriod state.

const { useState } = React;

const App = () => {
  const [image, setImage] = useState(null);
  const [timePeriod, setTimePeriod] = useState(null);
  
  const images = [
    "/test/static/media/its9-odc_d.9d5de720.png",
    "/test/static/media/its9-odc_m.178c1879.png",
    "/test/static/media/its9-odc_w.5e70ca59.png",
    "/test/static/media/its9-odc_y.8cf41473.png"
  ];
  
  const timePeriods = ['_d', '_m', '_w', '_y'];

  const handleClick = (v) => {
    const foundImage = images.find(name => name.includes(v));
    setImage(foundImage || null);
    setTimePeriod(v);
  }


  return <div>
  {timePeriod}
  <br />
  {image && <img src={image} />}
  <br />
  {timePeriods.map((v, i) => {
    return (
       <button onClick={() => handleClick(v)}>
          {v}
       </button>
    )
  })}
  </div>
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related