0

Hello I am new to react and have a question with changing classes and animation onClick.

I am trying to move up and down only with css classes that I add or remove to an array that is in my className.

app.js i have this in state

updown: ["containerMG"],

and here is how i render my components in app.js

  render() {

    return (
      <div>
      <div className="movies-container">
        {this.state.filmovi.map((film, index) => {
          return <Film
                    naslov={film.naslov}
                    naslovnaSlika={film.naslovnaSlika}
                    key={film.id}
                    openFilm={() => this.injectFilm(index)}/>
      })}
      </div>
      <Gallery />
      <ContainerMG
        selectedFilm={this.state.selectedFilm}
        klasa={this.state.updown}
        zatvori={this.closePreview}/>
      </div>
    );
  }

my component looks like this

const ContainerMG = (props) => {
  return (
      <div className={props.klasa.join(' ')}>
      <img onClick={props.zatvori} src="xxx" alt="close" className="close-popup" />
        <p>{props.selectedFilm.naslovFilma}</p>
      </div>
  )
}

this is how the div moves up

  injectFilm = (filmIndex) => {
    this.state.updown.push("position-top");
    const selectedFilm = this.state.filmovi.find((film, index) => index === filmIndex)
    this.setState((prevState) => ({
       selectedFilm
    }))
  }

this is how i tried to move it down

  closePreview = () => {
    this.state.updown.splice(1);
  }

i am pretty sure i should not change the state directly, and also when i change it to remove the "position-top" class the dom doesn't reload.

thank you for all the help in advance and if i didn't show something that you need please do write.

srdjan_susa
  • 111
  • 13

1 Answers1

1

You're right, you should never change the state directly like that, but rather, use a setState() method. Doing this.state.updown.push("position-top"); will mutate it. Let's say you want to remove whatever is last from the array, you could do something like:

const {updown} = this.state;
updown.pop();
this.setState({updown: updown});

Which would cause a re-render. Treat the state as if it were immutable.

Predrag Beocanin
  • 1,402
  • 3
  • 18
  • 25