Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda