0

Is it valid to use Javascript codes within a ReactJs project? I have something like this,

JS

myFunc(e) {
     let v = e.target.value

     if(v.length > 0) {
         e.target.parentNode.setAttribute('class', 'abc')
     }
     else {
         e.target.parentNode.setAttribute('class', 'xyz')
     }
}

HTML

<input ref="xxx" onBlur={this.myFunc.bind(this)} name="xxx" className="xxx" type="text">

This method works as I wanted but not sure weather it's safe to use such codes in ReactJs or not. Please advise me.

1 Answer 1

1

It works but generally this is not the promoted way to go. Since I don't know exactly what goes on in the rest of your code, below is my implementation based on your input above:

export default class BlurrableInput extends React.Component {
    constructor() {
        this.state = {
             text = null
        };
    }
    handleInputBlur() {
        console.log('Hello from blur');
    }
    handleInputChange(event) {
        this.setState({
            text: event.target.value
        });
    }
    render() {
        let className = this.state.text !== null && this.state.text.length > 0 ? 'abc' : 'xyz';
        return(
            <input 
                 ref='xxx' 
                 onBlur={this.handleInputBlur} 
                 value={this.state.text} 
                 name='xxx' 
                 className={className} 
                 type='text' />
        );
    }
}

Ps. For the classname generation I can highly recommend this library.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.