I currently set my active
state to 0:
const [active, setActive] = useState(0);
but I'm wondering how I can set the initial value to null
if one of my component props: isFilterMode
is true? So the initial state is "dynamic" based on the props?
Try like this
const [active, setActive] = useState(props.isFilterMode ? null : 0);
or using a callback function ( lazy initialization
)
const [active, setActive] = useState(() => props.isFilterMode ? null : 0);
const Component = ({ isFilterMode }) => {
const [active, setActive] = useState(() => isFilterMode ? null : 0);
...
}
you can define an expression with a return value as an argument for useState. With a ternary operator like props.isFilterMode? null: 0
props.isFilterMode? null: 0
you would return null
if the value of props.isFilterMode
evaluates to true and 0 otherwise. So in useState
you would have:
const [active, setActive] = useState(props.isFilterMode ? null : 0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.