Home > Software engineering >  Change Icon from FontAwesomeIcon on Function (onChange Text Input)
Change Icon from FontAwesomeIcon on Function (onChange Text Input)

Time:03-30

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>
      </>
    )
  }

}

CodePudding user response:

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>
    );
  }
}

CodePudding user response:

Maybe instead of passing an object you could try to pass a string for fa-search like so:

<FontAwesomeIcon icon='fas fas-search />

The implementation in onChange being:

if(event.target.value === ''){
      this.setState(
        'fa fa-shuffle', // don't know this one check it on https://fontawesome.com/v5/icons/random?s=solid
      )
    } else {
      this.setState(
        'fas fas-search'
      )
    }
  • Related