Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!