Home > Mobile >  Is there some way to change color of a label when the input which is a child element in sibling div
Is there some way to change color of a label when the input which is a child element in sibling div

Time:08-16

<form>
<label>Hello there</label>
    <div>
      <input/>
    </div>
</form>

Is there some way we can style the label when the input inside the div is brought into focus. Please give suggestion for React or HTML without the use of jQuery. For instance when the input is brought in focus, the color of the label changes.

CodePudding user response:

You can try label:focus-within { color: red; }.

This will style the label whenever any of its children has focus.

You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

CodePudding user response:

You can use this code:

export default function App() {
  const [focuse,setFocuse]=useState(false);
  return (
    <div className="App">
      <label style={{backgroundColor:focuse?'red':'transparent'}}>Hello there</label>
    <div>
      <input onFocus={()=>setFocuse(true)}/>
    </div>
    </div>
  );
}

CodePudding user response:

import * as React from 'react';

export default function App() {
  const [Color, setColor] = React.useState('#e31f1f');
  const newColor = '#1fe3b2';
  const OldColor = '#e31f1f';
  const changeCollorFunction = (color: string) => {
    setColor(color);
  };
  return (
    <div>
      <form>
        <label
          id="change-color"
          style={{
            color: Color,
          }}
        >
          Hello there
        </label>
        <div>
          <input
            type="text"
            onFocus={() => {
              changeCollorFunction(newColor);
            }}
            onBlur={() => {
              changeCollorFunction(OldColor);
            }}
          />
        </div>
      </form>
    </div>
  );
}

  • Related