Dynamically add a Font Awesome icon to the background of an input text field with React and react-fa

Utilizing ReactJs and react-fa to access Font Awesome icons, I am attempting to dynamically place one of the icons inside a text input.

The following is my code snippet:

    import React, { Component } from 'react';
    import PropTypes from 'prop-types';
    import { Icon } from 'react-fa';

    import '../index.css';

    class SearchInput extends Component {

        static propTypes = { 
          onKeyUp: PropTypes.object,
          placeholder: PropTypes.placeholder,
          iconName: PropTypes.string
        };


        handleKeyUp = (content) => {

            console.log(content);

        }

        render() {

                let icon = <Icon name={this.props.iconName} />;

                let extra = {
                    backgroundImage: icon
                }

                return (
                    <input className='ux-search-input' style={extra} type='text' onKeyUp={this.handleKeyUp} placeholder={this.props.placeholder} />
                    );
        }
    };

    export default SearchInput;

The icons are not appearing as expected. This is because the icon variable is a ReactJs component and not a URL to match.

Answer №1

When using react-fa, keep in mind that it renders as html using <i class="fa fa-name" />, meaning it cannot be used as a style. Instead, consider implementing it like this:

      return (
          <span>
             { icon }
             <input className='ux-search-input' style={extra} type='text' onKeyUp={this.handleKeyUp} placeholder={this.props.placeholder} />
          </span>
          );

Remember to style it accordingly to ensure proper icon positioning.

Answer №2

Instead of utilizing a React component, consider utilizing a standard icon tag preceding the input field, and then utilizing CSS to position the icon correctly.

Here is an example:

JSX:

<i class={this.props.iconName} id="icon" />

CSS:

#icon {
  // Adjust margins and position to fit the input background
  margin-left: 30px;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for retrieving the height of a Material UI Dialog using a ref?

In my React project, I have decided to utilize Material UI. Currently, I am faced with a challenge as I need to determine the height of a Dialog component. To achieve this, I attempted the following approach: import Dialog from '@material-ui/core/Dia ...

Why is my column getting devoured even though it has custom content tailored to it?

In my layout, I have one column, one row, and three nested columns. Each column contains a custom-designed button instead of using the default Bootstrap button. However, there seems to be an issue where one of the columns is getting cut off. To better und ...

I am looking for a solution on how to validate a token issued by Auth0 in a nodejs backend using jwt, but I keep

My React frontend uses Auth0 for user authentication. Once a user is logged in, I retrieve the token using getAccessTokenSilently() and send it to the backend like this: const { user, isAuthenticated, getAccessTokenSilently } = useAuth0() useEffect(() =&g ...

Communicating between Laravel and React: Sending notifications from Laravel to React without encountering the 'self' restricted-globals error

I want to create notifications in both Laravel and React, but I am facing an issue with sending the notification from Laravel to my React application. Here is the code snippet from my Laravel Controller: <?php namespace App\Http\Controllers; ...

Create queries for relays in a dynamic manner

I'm using Relay Modern for my client GraphQL interface and I am curious to know if it is possible to dynamically generate query statements within Relay Modern. For example, can I change the original query structure from: const ComponentQuery = graphq ...

Encountering a snag when trying to load JavaScript within an HTML document

I encountered an error while trying to load an HTML file in the JavaScript console of the Brave browser. The error message reads: require.js:5 Uncaught Error: Module name "constants.js" has not been loaded yet for context: _. Use require([]) https://requir ...

Implement a jQuery click event on a dynamically generated button in the code-behind

A button (Replybtn) is dynamically created when clicked in the code-behind file. --Default.aspx.cs-- protected void ReloadThePanelDetails_Click(object sender, EventArgs e) { litResultDetails.Text = litResultDetails.Text + "<button id='Replyb ...

Troubleshooting Node.js - MongoDB document removal issue

I am attempting to delete all documents from a collection that contain a field named uuid with values matching the $in operator along with an array I provide. However, for some reason the deletion is not functioning as expected. Below is the code snippet a ...

Enhance your webpage with dynamic styling using third-party CSS animation

Apologies for any similarity to other questions on this topic. I have searched extensively, but any assistance would be greatly appreciated. I am utilizing a new animation library from Animista to animate specific elements on a test website. Animating ele ...

Implementing a 'Load More' button for a list in Vue.js

I am currently working on adding a load more button to my code. While I could achieve this using JavaScript, I am facing difficulties implementing it in Vue.js. Here is the Vue code I have been working with. I attempted to target the element with the compa ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

I am curious about when the CSS of my website will start impacting its search engine ranking

Initially, my perception of CSS was that it was only used for styling the appearance of a document when viewed in a browser. However, I soon came to realize that search engines also utilize CSS for indexing web pages. It is said that search engines do not ...

There is no response provided by the function

Here is the code for inserting data into the database. However, it seems to be going into the else section as the response is empty. I have checked by alerting the response, but it remains empty. // Function to add donation via AJAX function ccjkfound ...

What is the reason that I have to submit my mapped function twice in order for the updated state to show after modifying the array content?

When I try to display an image for the current value in the array item, the image does not display when I submit my value. I have to submit twice to display the value. Additionally, when changing the value and pressing submit, the content in the div does ...

What is the best way to automatically hide the Materialize CSS mobile navbar?

Recently, I completed a website called Link. Using only Materialize CSS, Vanilla JS, and plain CSS, I developed a single-page application that effectively hides and reveals different sections based on event listeners. Everything functions smoothly except ...

The swf file doesn't stretch to fit the window when the height is set to 100%

Struggling with creating a flash recorder controlled by JavaScript? Trying to get the flash to fill the browser window but disappearing when setting height or width to 100%? Where am I going wrong? <div id="flashrecorder"> <object wmode="trans ...

Unable to switch the text option

[Fiddle] I'm currently working on a project where I want pairs of buttons to toggle text by matching data attributes. While I can successfully change the text from "Add" to "Remove" on click, I am facing an issue with toggling it back to "Add" on the ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

Easily retrieve JSON information using ReactJS

I received a JSON response that looks like this: { "message": "OK", "data": [ { "id": 5, "full_name": "John Donovan", "username": &quo ...

Trouble Arising from the Lack of Coordination Between CSS Transition and JavaScript Update Triggered by Element

I'm currently working on a web development project that involves a list of clickable elements. When one of these elements is clicked, it should become active and trigger a CSS transition (such as a transform) with a duration of 200ms. Additionally, I ...