Search code examples
cssreactjsstyling

Adding Condition in Styling using its own or parent's css property as condition in REACT


Recently, I was working in a React project, And it got me thinking if i can use react style propery as condition.
Here's my working code \

const {_,width} = useDimensionHook()
<Component
     styles={{
       position: width < 991 ? "absolute" : "fixed",
       top: width < 991 ? 0 : 42
     }}
/>

What I want to know if I can do something like,

const {_,width} = useDimensionHook()
<Component
     styles={{
       position: width < 991 ? "absolute" : "fixed",
       top: position == 'absolute' ? 0 : 42 
          // using css property **position** inside same styling
     }}
/>

I need your suggestions. Maybe applying parent first and then use that styling in its children. But I don't know the exact answer. Need your help
Thanks


Solution

  • You can definitely do that by simple storing the computed value of position in a variable, and then using it in a ternary statement. On top of that, you can take advantage of useMemo to return a memoized value:

    const {_,width} = useDimensionHook();
    const myCustomStyles = useMemo(() => {
         const position = width < 991 ? 'absolute' : 'fixed';
    
         return {
              position,
              top: position === 'absolute' ? 0 : 42,
         }
    }, [width]);
    
    <Component styles={myCustomStyles} />