import React, { Component } from "react";
class NavBtn extends Component {
state = {
styles: {
width: 0,
}
};
handleClick = () => {
this.setState(oldState => {
return {
styles: {
width: oldState.width + 100,
}
};
});
};
render() {
return (
<div>
{/* navigation icon */}
<div className="navbtn" onClick={this.handleClick}>
<div className="bar" />
<div className="bar" />
<div className="bar" />
</div>
{/* form pannel */}
<div
className="formPannel-container"
style={{ width: `${this.state.styles.width}px` }}
/>
</div>
);
}
}
export default NavBtn;
why doesn’t my setState not set a new state with this code above. It’s not accessing plus changing it and I don’t know why.
Thank you!
Silas
React does not play well with nested objects. It does not recognize when nested properties change. To get around this, you can do something like the following or rethink how you could use non-nested Objects for state.
handleClick = () => {
this.setState(oldState => {
const styles = { ...oldState.styles };
styles.width += 100;
return { styles, }
});
};
or a more condensed version:
handleClick = () => {
this.setState(({ styles }) => ({ styles: { width: styles.width += 100, } }));
};
1 Like
Thanks for getting back with me. That’s really strange that it does’t play well with nested objects. Maybe to keep the state as simple as possible? Anyways, thanks for helping me solve my problem and future problems!
Also, do you know any great resources that teaches JS promises for beginners like me? And also Redux with React?
Silas
1 Like
Not sure about Promises as I’m looking for good resources for that topic as well.
For React + Redux though, have you tried reading the quick start section of the react-redux
documentation here? There’s a tutorial as well.
Awesome! I’ve been looking and I didn’t even come across this. Thank you for sharing! I’ll let you know if I find anything on promises.
Thank you for the help!
Silas
1 Like
Glad to help!
And yeah, if you’re interested in more discussion regarding nested states in React, you can read this StackOverflow thread.
Have fun learning.
1 Like