dfassf
dfassf

Reputation: 172

changing an element's className doesn't work properly

I want to change the color of an element by switching className, and the className is not changing.

I am currently using nextJS and mobX.

here is the example code:

Example.tsx

<div 
  className = {store.isChosen ? 'isChosen' : 'isNotChosen'}
  onClick={()=>{
    store.isChosen = !store.isChosen;
  }}
>ELEMENT</div>

// this doesn't work either
<div 
  className = {store.isChosen ? `{styles.isChosen}` : {styles.isNotChosen}`}
  onClick={()=>{
    store.isChosen = !store.isChosen;
  }}
>ELEMENT</div>

ExampleStore.ts

@observable
isChosen:boolean = false;

Example.module.scss

.isChosen{
  background-color: red;
}

.isNotChosen{
  background-color: blue;
}

Upvotes: 0

Views: 69

Answers (1)

Riadh Adrani
Riadh Adrani

Reputation: 615

An observable in Mobx is, as its name suggest, observed for any change that can affect it, that's why when you just set the value to something new, it directly reflected. You can even create an observable object and update the values inside like : myState.stateKey = "new Value" and it would work too thanks to Proxy.

I invite you to read docs for more infos.

Upvotes: 1

Related Questions