How to conditional render in Chakra UI?

Viewed 1638

I'm rendering two Chakra UI components based in a variable loading:

{loading ? (<Spinner>) : (<Text color={useColorModeValue('gray.800', 'gray.400')>Hi</Text) }

But the IDE is warning me about this: ESLint: React Hook "useColorModeValue" is called conditionally. React Hooks must be called in the exact same order in every component render.

How should I render those components? useColorModeValue is a hook

2 Answers

useColorModeValue is a React hook, so it can't be conditionally called, it is breaking the Rules of Hooks. Using a ternary is a way to conditionally call it. The hook must be called each and every render cycle.

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Pull the useColorModeValue out into the body of the function component and save the returned color value to be passed later to the Text component.

const color = useColorModeValue('gray.800', 'gray.400');

...

{loading ? <Spinner> : <Text color={color}>Hi</Text>}

You can conditionally render a property within a Chakra UI component by creating a constant that takes a value and returns the desired property string based on defined conditions. This example was made using React.

const colorChange = (value) => {
    let color
    if (value >= 0){
        color = "green"
    } else {
        color = "red"
    }
    return color
  }

<Text color={colorChange(value)}>

I googled the title exactly when trying to solve this issue, and found no resources. So I'm hoping this response can help someone who's ran into this same issue. Cheers!

Related