Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

try to keep state as simple as possible, and toggle styles/classnames based on state #17

Open
rooberrydev opened this issue Oct 26, 2020 · 1 comment

Comments

@rooberrydev
Copy link

rooberrydev commented Oct 26, 2020

const [sidebarWidth, setSidebarWidth] = React.useState('13rem');
const collapse = () => setSidebarWidth('0');
const unfurl = () => setSidebarWidth('13rem');

Setting a width value with state isn't ideal, if you have a more complex difference in the UI, it can be quite difficult to store all that information in state.

At a basic level, this state value tracks whether the sidebar is open, or not.

So calling it isOpen or something similar, and having a true/false value is recommended.

const [isOpen,setIsOpen] = React.useState(true)
 const collapse = () => setIsOpen(false); 
 const unfurl = () => setIsOpen(true)

Now you can conditionally change classNames or inline styles depending on this state value.

<Nav style={{ width: isOpen ? '13rem' : '0' }}></Nav>;

It seems like more effort in this example since only width is changing, but if we have a more complex UI change it's not ideal to store the css values directly in state. Instead store a boolean describing the state, and set classNames or styles depending on that boolean.

@rooberrydev
Copy link
Author

This is actually insignificant here since only width is changing. But I thought I'd mention it anyway, good to practice common react patterns!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant