How to apply css to parent element when child focused in Mui V5?

Viewed 316

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.

2 Answers

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.

Here is my solution with onFocus event and onBlur events

import * as React from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";

export default function FullWidthTextField() {
  const [focus, setFocus] = React.useState(false);
  const toggle = () => setFocus(!focus);

  const handleOnFocus = () => {
    toggle();
  };

  const handleOnblur = () => {
    toggle();
  };

  React.useEffect(() => {
    console.log(focus);
  }, [focus]);

  return (
    <Box
      sx={{
        width: focus ? "80%" : "10%",
        padding: 2,
        margin: 2,
        transition: "width 1s ease-in-out",
        // boxShadow: 3
        boxShadow: 21
      }}
    >
      <TextField
        fullWidth
        label="fullWidth"
        id="fullWidth"
        onFocus={handleOnFocus}
        onBlur={handleOnblur}
      />
    </Box>
  );
}

You can try out the demo here: DEMO

Related