Home > Software design >  How to apply css to parent element when child focused in Mui V5?
How to apply css to parent element when child focused in Mui V5?

Time:01-06

As a simple demonstration, I made this code sandbox example. I want to apply some styles to the Box component when the Text field is focused. In my use case, I can apply styles in the text field's class instant of the parent box. But I wonder how parent box knows a child is focused or not then apply css accordingly.

CodePudding user response:

The easiest thing to do would be to handle the onFocus and onBlur event of the text field, and then add additional props to the parent element when the text box is focused.

export default function FullWidthTextField() {
  const [textFieldFocused, setTextFieldFocused] = React.useState(false);

  const extraProps = textFieldFocused
    ? { backgroundColor: "orange" } 
    : {};

  const sx = {
    // ... default styles for the box
    ...extraProps
  };

  return (
    <Box sx={sx}>
      <TextField
        fullWidth
        label="fullWidth"
        id="fullWidth"
        onFocus={() => setTextFieldFocused(true)}
        onBlur={() => setTextFieldFocused(false)}
      />
    </Box>
  );
}

Here's an updated demo showing this solution in action.

CodePudding user response:

Here is my solution with onFocus event and onBlur event:

Demo: https://codesandbox.io/s/can-parent-know-child-focuses-sofq-material-demo-forked-sbjvl?file=/demo.js

  •  Tags:  
  • Related