#Is there a way to programmatically change sx identifiers?

12 messages ยท Page 1 of 1 (latest)

marble tundra
#
<Box sx={{
        position: 'absolute',
        bottom: 40,
        left: 40,
        transform: `scale(${scale})`,
        opacity: `${opacity}%`,
        transition: 'opacity 0.25s ease'
      }}>

I have this box, but I would like to be able to programatically change left: 40 to right: 40.
Is there any reasonable way to do this?

potent bone
# marble tundra ```ts <Box sx={{ position: 'absolute', bottom: 40, left:...

You can conditionally spread sx prop:
<Box {...(true ? { sx: { left: 40 } } : { sx: { right: 40 } })} />

Or conditionally spread specific properties in sx:
<Box sx={{ position: 'absolute', bottom: 40, ...(true ? { left: 40 } : { right: 40 }), transform:scale(${scale}), opacity: ${opacity}%, transition: 'opacity 0.25s ease', }} />

marble tundra
#

Thanks I will give this a shot! Could you give an example of using a state hook to control the value using this though?

potent bone
#
const [shouldMove, setShouldMove] = useState(false)

  return (
    <Box
      sx={{
        position: 'absolute',
        bottom: 40,
        ...(shouldMove ? { left: 40 } : { right: 40 }),
        transform: scale(${scale}),
        opacity: `${opacity}%`,
        transition: 'opacity 0.25s ease',
      }}
    />
  )

not Sure if this is what you meant

marble tundra
#

Yes that should be perfect thanks ๐Ÿ™

potent bone
#

Welcome ๐Ÿ™‚

marble tundra
#

Works great ๐Ÿ”ฅ

marble tundra
# potent bone ``` const [shouldMove, setShouldMove] = useState(false) return ( <Box ...

Hey so I'm actually having some trouble getting this to work in my actual setup. It works well when I just toggle it with a button, but has some issues with how I did it.

This is in my app.tsx component

const [ useLeftAnchor, setUseLeftAnchor ] = useState(false)

...

useEffect(() => {
  console.log(`useEffect ${useLeftAnchor}`)
}, [useLeftAnchor])
    
...

<Box sx={{
  position: 'absolute',
  bottom: 40,
  ...(useLeftAnchor ? { left: 40 } : { right: 40 }),
  transform: `scale(${scale})`,
  opacity: `${opacity}%`,
  transition: 'opacity 0.25s ease'
  }}>
</Box>

...

<Menu useLeftAnchor={useLeftAnchor} setUseLeftAnchor={setUseLeftAnchor}/>

I have this in the menu component, and I passed the useState as props.

<SegmentedControl sx={{float: 'right'}} 
  value={useLeftAnchor}
  onChange={setUseLeftAnchor}
  data={[
    {label: 'Right', value: 'false'},
    {label: 'Left', value: 'true'}
  ]
}/>
#

The useEffect i added to app.tsx does print the correct value when the control is toggled

#

and this button (which is in app.tsx) does make it swap properly

<Button onClick={() => {if (useLeftAnchor) {setUseLeftAnchor(false)} else {setUseLeftAnchor(true)}}}>Anchor</Button>
marble tundra
#

I resolved this by changing my state hook type from boolean to string to match the segmented control

north sigil