Below is my form.jsx file
var React = require('react');
var Input = require('./input');
module.exports = React.createClass({
getInitialState: function() {
return {
focus: false
}
},
render: function () {
return <div className="info_input">
<div className="demo demo2 lll">
<div className={"css " + (this.state.focus ? "active" : "")}>
<label htmlFor="d3">{this.props.firstCol}</label>
<Input id="d3" type="text" handleFocus={this.addClass} handleBlur={this.removeClass} />
</div>
</div>
<div className="demo demo2">
<div className={"css " + (this.state.focus ? "active" : "")}>
<label htmlFor="d3">{this.props.secondCol}</label>
<Input id="d3" type="text" />
</div>
</div>
<div className="clear"></div>
</div>
},
addClass: function () {
this.setState({
focus: true
});
},
removeClass: function () {
this.setState({
focus: false
});
}
});
and this is my Input component .jsx file
var React = require('react');
module.exports = React.createClass({
getInitialState: function () {
return {
focus: false
}
},
render: function() {
return <input id={this.props.id}
type={this.props.type}
onFocus={this.props.handleFocus}
onBlur={this.props.handleBlur}
autofocus={this.state.focus} />
}
});
If I focus on input field, it will add "active" className to its parent div. However, all input field will also be added "active" class.
How can I do to only add class to parent div of focused input not all of them.
Since you have some simple logic (adding classes when focusing), it is a good idea to wrap this into a component and wrap this logic into it.
So, I've made a simple example:
https://jsfiddle.net/hLuv0c65/1/
It basically creates an Input component and adds input--focused
to the parent div if the input is focused:
var Input = React.createClass({
getInitialState: function() {
return {
isFocused: false
};
},
onFocus: function() {
this.setState({
isFocused: true
});
},
onBlur: function() {
this.setState({
isFocused: false
});
},
render: function() {
var classes = [];
if(this.state.isFocused) {
classes.push('input--focused');
}
return (
<div className={classes.join(' ')}>
<input
type="text"
onFocus={this.onFocus}
onBlur={this.onBlur} />
</div>
);
}
});
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With