Home > Software design >  How to pass variable to MUI styled function in ReactJS
How to pass variable to MUI styled function in ReactJS

Time:08-03

How can I pass variable to conditionally change styles properties while using MUI styled function? I want to achieve this: borderColor: darkMode ? 'white' : 'black'

const StyledSelect = styled(Select)(() => ({
  "& fieldset": {
      borderColor: 'dark',
  }
}));

function BasicSelect() {

  const { darkMode }= useSelector((state: {options: {darkMode: boolean}})=>state.options)

  const [age, setAge] = React.useState('');

  const handleChange = (event: SelectChangeEvent) => {
    setAge(event.target.value as string);
  };

  return (
      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Age</InputLabel>
        <StyledSelect
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={handleChange}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
  );
}

One of the options that works is to make function and pass it to sx prop like this, but I wonder if it is possible to pass variable directly to styled function

const selectstyles = (darkMode) => ({
    "& fieldset": {
        borderColor: darkMode ? 'white' : 'black'
 }
})

<StyledSelect sx={selectStyles(darkMode)} ...></StyledSelect>

CodePudding user response:

The same question was asked here: https://stackoverflow.com/a/69341672/8972840 This will help you pass props through the styled() function.

  • Related