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
CodePudding user response:
You can set styles in a constant and then use that to check it's value for your condition
like this :
const {_,width} = useDimensionHook()
const componentStyles = {
position: width < 991 ? 'absolute' : 'fixed',
};
return (
<Component
styles={{
...componentStyles,
top: componentStyles.position == 'absolute' ? 0 : 42,
}}
/>
);
CodePudding user response:
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} />