Alessander Franca
Alessander Franca

Reputation: 2753

react className not updating when state changes

I have a TextInput component that updates the className.

class TextInput extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            errorVisible: false,
            textErrorClass: '',
            errorMessage: ''
        }
        this.onChange = this.onChange.bind(this);
    }

    onChange(ev){
        let isValid = true,
            errorMessage = '';
        const value = ev.target.value;

        if(this.props.required && value.length === 0){
            isValid = false;
            errorMessage = 'Campo obrigatório';

        }
        else if(this.props.minLength > 1 && value.length < this.props.minLength && value.length > 0){
            isValid = false;
            errorMessage = `Campo deve possuir pelo menos ${this.props.minLength} caracteres`;
        }

        this.props.onChange(ev, isValid);

        this.setState({
            errorVisible: !isValid,
            textErrorClass: isValid ? '' : this.props.textErrorClass,
            errorMessage,
        })
    }

    render(){
        console.log(this.state.errorVisible ? this.props.errorClass : this.props.inputClass);
        return(
                <div>
                    <input className={this.state.errorVisible ? this.props.errorClass : this.props.inputClass}
                      type={this.props.type}
                      name={this.props.name}
                      placeholder={this.props.text}
                      maxLength={this.props.maxLength}
                      className={this.props.inputClass}
                      onChange={this.onChange}
                      defaultValue={this.props.defaultValue}
                    />
                    {this.state.errorVisible && <div className={this.state.textErrorClass}>{this.state.errorMessage}</div> }
                </div>
        );
    }
}

The log console.log(this.state.errorVisible ? this.props.errorClass : this.props.inputClass) works correctly, but the className does not work.

Any idea about this problem?

Thanks in advance.

Upvotes: 2

Views: 4598

Answers (2)

Varad Nadkarni
Varad Nadkarni

Reputation: 31

I have a solution for this in general. Many a times if we use variables as classnames, they don't get updated. We can use inline styling instead. This is only a quick hack and it is better to find out why classnames are not updating.

Upvotes: 0

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93203

Because you wrote it twice, where the second overrides the first

<input
   className={this.state.errorVisible ? this.props.errorClass : this.props.inputClass}
   //...
   className={this.props.inputClass}
 />

Keep the 1ˢᵗ and remove the 2ⁿᵈ which is className={this.props.inputClass}

Upvotes: 3

Related Questions