A
A
Alex Ozerov2020-07-11 22:26:37
React
Alex Ozerov, 2020-07-11 22:26:37

How to change color when input loses focus?

In the code, I wrote that when I click on the input, the container changes the background, but how to make it so that when the focus is lost by the input, the background of the input becomes back to default?

import React from "react";
import sr from './Search.module.css';
import icon from './../../../../img/grey_search.svg';

class Search extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            'activeColor': "#224B7A"
        }
    }
    changeColor = () =>{
        this.setState({'activeColor': "#fff"})

    }
    render() {
        let bg = {backgroundColor: this.state.activeColor}
        return (
            <div className={sr.container} style={bg}>
                <div className={sr.search}>
                    <form action="#">
                        <div className={sr.wrapper__form}>
                            <div className={sr.form__icon}>
                                <img src={icon} alt="image"/>
                            </div>
                            <div className={sr.form__input}>
                                <input type="text" placeholder='Поиск'  onClick={this.changeColor}/>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        );
    }
}
export default Search;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-07-11
@ozerovlife

.container {
  background: #224B7A;
}

.container.active {
  background: #fff;
}

state = {
  active: false,
}

toggleActive = ({ type }) => {
  this.setState(() => ({
    active: type === 'focus',
  }));
}

<div className={`container ${this.state.active ? 'active' : ''}`}>
  ...
  <input onFocus={this.toggleActive} onBlur={this.toggleActive} />

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question