'Why doesn't MobX observables work with ternary operators?
Does anyone know why MobX observables can't re-render conditionally rendered components using the ternary operator? I'm using version 5 of MobX. To be clear, the first render works fine, showComponent1 will be true and React will render Component1. But if you click the button to change showComponent1 to false, no re-render will happen and it will still show Component1 even though showComponent is false. This is shown in the example below.
import { observer } from "mobx-react";
import { observable } from "mobx";
@observer
class MyComponent extends React.Component {
@observable
showComponent1 = false;
render() {
return (
<>
{this.showComponent1
? <Component1 />
: <Component2 />
}
<button onClick={() => showComponent1 = true})>Show Component 2</button>
</>
)
}
}
However, if I assign the observable to a variable with the render function, React will observe any changes to showComponent1 observable and re-render the correct component. Does anyone know why this is happening and a better way of resolving this than re-assigning the observable?
import { observer } from "mobx-react";
import { observable } from "mobx";
@observer
class MyComponent extends React.Component {
@observable
showComponent1 = false;
render() {
const show1 = this.showComponent1;
return (
<>
{show1
? <Component1 />
: <Component2 />
}
<button onClick={() => showComponent1 = true})>Show Component 2</button>
</>
)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
