I’m thinking about changing the icon which is set using the fontawesome-react package depending on a previous user interaction.
On screen the user has a input field and button (which contains an icon). If the Input is empty a different icon is presented
No User Input:
+-----------------------+-----------+
| Search Placeholder... | (Shuffle) |
+-----------------------+-----------+
User Input:
+-----------------------+-----------+
| Value | (Search) |
+-----------------------+-----------+
when setting the icon manually inside the <FontAwesomeIcon> I’m able to find faSearch, When however setting it using state I get the error:
Could not find icon {prefix: 'fas', iconName: 'faSearch'}
Here’s my take so far. I’d be really happy if someone is able to assist and is able to explain what I’m missing.
class Search extends React.Component {
state = {
displayIcon: "faSearch",
}
onChange(event) {
console.log(event.target.value)
if(event.target.value === ''){
this.setState({
displayIcon: "faShuffle",
})
} else {
this.setState({
displayIcon: "faSearch",
})
}
}
render(){
const { displayIcon } = this.state //destucture state
console.log( );
return (
<>
<InputGroup className="mb-3">
<FormControl
placeholder="search or feel lucky..."
onChange={this.onChange}
/>
<Button variant="primary" id="search" size="lg">
<FontAwesomeIcon icon={displayIcon} />
</Button>
</InputGroup>
</>
)
}
}
>Solution :
you can also do that like this and render it conditionally:
class Search extends React.Component {
state = {
value: '',
};
onChange(event) {
this.setState({
value: event.target.value,
});
}
render() {
const { value } = this.state; //destucture state
return (
<InputGroup className='mb-3'>
<FormControl placeholder='search or feel lucky...' onChange={this.onChange} />
<Button variant='primary' id='search' size='lg'>
{value ? <FontAwesomeIcon icon={faSearch} /> : <FontAwesomeIcon icon={faShuffle} />}
</Button>
</InputGroup>
);
}
}