I'm learning to implement Unstated in my react app.
I made a simple app that shows a Note using Unstated.
This is my NoteContainer:
class NoteContainer extends Container {
state = {
title: 'My Note',
desc: 'This note state is managed with unstated',
isDisplaying: false,
}
constructor() {
super()
this.show = this.show.bind(this);
}
show() {
this.setState({ isDisplaying: !this.state.isDisplaying })
console.log(this.state);
}
}
As you see, is really simple, it just change the isDisplaying property in the state so i can use it on Note.js component to show the title and the message of the note like this:
class Note extends Component {
state = {
isShowing: false,
}
render() {
if (this.state.isShowing) {
return (
<Subscribe to={[NoteContainer]}>
{noteContainer => (
<div className="container">
<p>{noteContainer.state.title}</p>
<p>{noteContainer.state.desc}</p>
</div>
)}
</Subscribe>
)
}
return (
<Subscribe to={[NoteContainer]}>
{noteContainer => (
<div className="container">
<button className="btn btn-success" onClick={() => {
noteContainer.show();
this.setState({
isShowing: noteContainer.state.isDisplaying,
})
console.log(this.state);
}}>
See Note!
</button>
</div>
)}
</Subscribe>
)
}
}
The desired functionallity is that when i click the See Note! button, it shows the title and the description of the note above the button, and if i click it again, it hides them.
However, what i obtain is that it creates another Subscribe component and this appears to delete the "See Note!" button part. Here is an image of the result.
The problem it's that i cant use the button again to hide the note information, i'm clearly using the subscribe component wrong, but i can't figure another way to use a conditional using unstated, so any help on this would be appreciated.
Thanks in advance, have a nice week!
I've managed to solve it with an inline if conditional. However i don't feel confortable about this solution, i would like to know how to implement a complete if conditional, so if anyone knows please leave a comment!
render() {
return (
<Subscribe to={[NoteContainer]}>
{noteContainer => (
<div className="container">
<p>{noteContainer.state.isDisplaying ? noteContainer.state.title : ''}</p>
<p>{noteContainer.state.isDisplaying ? noteContainer.state.desc : ''}</p>
<button className="btn btn-success" onClick={() => {
noteContainer.show();
}}>
See Note!
</button>
</div>
)}
</Subscribe>
)
}