Home > OS >  How do I change css class of parent if input field is focused
How do I change css class of parent if input field is focused

Time:11-09

im trying to make a search box with a magnifying glass icon that becomes blue when the input field is focused.

the MagnifyingGlass component inherits its color from its parent element.

import styles from './Search.module.sass';
import { useState } from 'react';
import MagnifyingGlass from '../../icons/MagnifyingGlass';


const Search = () => {
  

  const [inputValue, setInputValue] = useState('');
  

  const handleChange = (e) => {
    setInputValue(e.target.value);
    
  };

  return (
    <div className={styles.searchWrapper}>
      <input
        value={inputValue}
        onChange={handleChange}
        className={styles.searchInput}
        type='text'
        placeholder='Waar bent u naar opzoek?'
     
      />
      <span> // needs to contain a className that results in the color to change
        <MagnifyingGlass size='small' /> // inherits color from parent
      </span>
    </div>
  );
};
export default Search;

CodePudding user response:

use onFocus and onBlur events

const Search = () => {
  

  const [inputValue, setInputValue] = useState('');
  
  const [show, toggle] = useState(false);
  
  const eventHandlers = useMemo(() => ({
    onFocus: () => toggle(true),
    onBlur: () => toggle(false),
  }), []);

  const handleChange = (e) => {
    setInputValue(e.target.value);
    
  };

  return (
    <div className={styles.searchWrapper}>
      <input
        value={inputValue}
        onChange={handleChange}
        className={styles.searchInput}
        type='text'
        placeholder='Waar bent u naar opzoek?'
        {...eventHandlers} 
      />
      <span className={show ? 'your_class': ''}> // needs to contain a className that results in the color to change
        <MagnifyingGlass size='small' /> // inherits color from parent
      </span>
    </div>
  );
};
export default Search;

CodePudding user response:

You don't need to change any class on the parent element, you can just use the css :focus-within pseudo-selector.

According to MDN the :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused.

Here is an example:

.wrapper {
  padding: 1rem;
  width: fit-content;
  border: 1px solid green;
}

.wrapper:focus-within {
  border: 1px solid blue;
}

.wrapper p {
  color: green;
}

.wrapper:focus-within p {
  color: blue;
}
<div >
  <p>this is a text</p>
  <input type="text">
</div>

You can read more about it here on MDN or here on CSS-Tricks

  • Related