0

I have an array that contains <SnackBar> elements:

const [snackbars,setSnackbars]=useState([
    <ReactSnackBar Show={true}>
       Snackbar 1
       <Icon onClick={snackbars.pop()}/>
    </ReactSnackBar>,
    ...
]}

I want to click on the <Icon/>, to remove this current snackbar, so that the next snackbar becomes visible. But this doesn't work with the error

ReferenceError: can't access lexical declaration `snackbars' before initialization

If I use a helper function inside the onClick it's the same.

Are there any suggestions on how to solve that?

OttherCreek
  • 615
  • 1
  • 6
  • 18
  • `onClick={snackbars.pop()}` means you're assigning the return value of `snackbars.pop()` to `onClick`. What you actually want is to create a new inline function that will call `snackbars.pop()` when clicked: `onClick={() => snackbars.pop()}` – Brian Thompson May 26 '20 at 13:55
  • But that's just the first problem. `pop` mutates the original array, this is wrong when dealing with react state. State should be treated as immutable. Second, storing JSX directly in state is usually not a great idea. Instead store some identifier for each component and map over it in the render to get your snackbars JSX. – Brian Thompson May 26 '20 at 13:57

0 Answers0