Reputation: 73
I wonder which way is better to display the value in case if you got value === 0.
This is what I came up with, but it doesn't look really clean:
const [value, setValue] = useState(propsValue === 0 ? 0 : propsValue || '');
I can't write this :
const [value, setValue] = useState(propsValue || '');
because in this case value === false and won't be displayed at all.
Upvotes: 0
Views: 42
Reputation:
The solution that works for all browsers would be :
(propsValue !== undefined && propsValue !== null) ? propsValue : ''
Upvotes: 1
Reputation: 13662
You can use the nullish coalescing operator to fallback to ''
only if propsValue
is either null
or undefined
.
useState(propsValue ?? '')
As a side-note, do remember that the parameter you're passing to useState
is the initial value so if the prop value changes, the state will not. If you want the value to update whenever the prop updates, just use the prop value itself instead of an intermediatery state.
Upvotes: 3