Reputation: 1297
I have a Search input on my page. I want to change the color (from silver to green) whenever the search length is equal or greater than 1. This code is kind of broken. Now there are 2 problems: 1) It changes color after the length of search is equal to 2 or greater.
2) It does not revert back to it's original color (silver) when search field is empty after I clear whatever I input in my search field.
Please help!
export let change = 'bg-silver';
class Card extends Component {
constructor({props, name, id, changeColor, change}) {
super(props, name, id, changeColor, change);
this.state = {
isToggleOn: true,
name: name,
id: id,
changeColor: changeColor,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
const { name, id, changeColor, isToggleOn} = this.state;
(changeColor.length > 1) ? change = 'bg-light-green'
: change = change;
return (
isToggleOn ?
<a style={{width: 200, height: 250}} className={'tc ' + change + ' dib br3 ma2 pa2 grow bw2 shadow-5'} onClick={this.handleClick}>
<h2 className='f6 measure-narrow lh-copy'>{name}</h2>
</a>
: <div style={{width: 200, height: 250}} className='flex-wrap justify-center bg-light-green dib v-top ma2 br3 pa2 bw2 grow shadow-5' onClick={this.handleClick}>
<p className='tc f6 measure-narrow lh-copy bg-silver br3 pa1 dib ma2 bw2 shawdow-5' >Hello, My name is <strong>{name}</strong><br/>
How are you?</p>
</div>
);
}
}
export default Card;
Upvotes: 1
Views: 108
Reputation: 1975
you need to change 2 things here:
change = (changeColor.length >= 1) ? 'bg-light-green' : 'bg-silver';
In your handleClick ()
- change setState
with this
this.setState({ isToggleOn: !this.state.isToggleOn });
Upvotes: 1
Reputation: 10003
1) changeColor.length > 1
- this means '2 or greater'. If you want '1 or greater' - use > 0
or >= 1
2) You have set variable change value to 'bg-light-green' once. Using change = change
will not do anything (assigning var to self).
Try:
change = (changeColor.length >= 1) ? 'bg-light-green' : 'bg-silver';
Upvotes: 2