How to change font-size from TextField when is focused?

Viewed 62

I'm beginner in ReactJS and I'm using materia-ui to create a page.

I need to do a custom on a TextField, I'd like to change the font-size when the input field is filled with some text. When I change the font-size, there is a very large space between the label and the border-bottom of the Input field. So I need to change the font-size only when the Input field is filled.

Could u tell me how can I do that?

Here's my code I put into codesandbox

import React from "react";
import * as S from "./styles";

export default function App() {
  return (
    <div className="App">
      <S.Input label="Name" variant="standard" />
    </div>
  );
}
import styled from "styled-components";

import { TextField } from "@mui/material";

export const Input = styled(TextField)`
  && {
    .MuiInputBase-root {
      font-size: 30px;
    }
  }
`;

Thank you very much for any help.

enter image description here

enter image description here

enter image description here

enter image description here

2 Answers

Here's a couple of ways, keep in mind I have never really used mui components.

Both involve magic numbers which aren't the best practice being completely honest.

The first solution involves adjusting the y position of the label initially, and when the text area is focused. sandbox link

export const Input = styled(TextField)`
  && {
    .MuiInputBase-root {
      font-size: 30px;
    }
    .MuiInputLabel-root {
      transform: translateY(40px);
    }
    .Mui-focused {
      transform: translateY(0px);
    }
  }
`;

The second approach is similar, but uses line-height instead. Again, using focused and initial label classes.

export const Input = styled(TextField)`
  && {
    .MuiInputBase-root {
      font-size: 30px;
    }
    .MuiInputLabel-root {
      line-height: 60px;
    }
    .Mui-focused {
      line-height: 22px;
    }
  }
`;

A css-only approach would be using :placeholder-shown pseudo selector.

The placeholder text will only be shown if an input is empty/not populated.

label{
  user-select:none;
  display:block;
}

input{
  border:none;
  border-bottom:1px solid #000;
  transition:0.3s;
}

input:invalid,
input:placeholder-shown{
  transform:translateY(-75%);
  background:transparent;
}

input::placeholder {
  color: transparent;
}


input:focus{
  transform:translateY(0%);
  font-size:2em;
  outline:none;
  border-bottom:1px solid red;
}
<p>
  <label>Name</label>
  <input class="MuiInput-input" value="" placeholder="placeholder">
</p>
<p>
  <label>Last name*</label>
  <input type="text" class="MuiInput-input" value="" required>
</p>

Support for this pseudoselector is pretty solid: See caniuse record.

As an alternative you might use input:invalid selectors for required fields in a similar way.

Related