The error "SearchIcon is not defined" is being thrown because it is not declared or referenced in the

My attempt to include a search icon within my search bar has hit a roadblock with the code I'm using. Here is what I have:

import React, { useEffect } from "react";

//31915c5e

const API_URL = 'http://www.omdbapi.com?apikey = 31915c5e'

const App = () => {
 
    const searchMovies = async (title) => {
        const response = await fetch(`${API_URL}&s=${title}`);
        const data = await response.json();

        console.log(data.search); 
    }

    useEffect(() => {
        searchMovies('spiderman');
    }, []);



    return (
        <div className="app">
            <h1>MovieLand</h1>

            <div className="search">
                <input
                    placeholder="search for movies"
                />

            /*https://react-icons.github.io/react-icons/icons?name=gi*/
                <img
                    src={SearchIcon}
                    alt="search"

                />

            </div>

        </div>
    );
}

export default App;

I am struggling to display a search icon within my search bar. When inspecting the browser, it shows 'SearchIcon' as not defined (no-undef).

Answer №1

To achieve this effect, you have a couple of options at your disposal. One approach is to go with installing @fortawesome/react-fontawesome and @fortawesome/free-solid-svg-icons to implement it that way. Another option would be using inline styles to position the icon as a background for the input tag; the code snippet below illustrates how this can be done:

import React, { useState } from "react";
import searchIcon from "path/to/search-icon.svg";

function SearchInput() {
  const [searchTerm, setSearchTerm] = useState("");

  return (
    <div>
      <input
        type="text"
        placeholder="Search"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        style={{
          padding: "0.5rem 0.5rem 0.5rem 2rem",
          background: `url(${searchIcon}) no-repeat`,
          backgroundSize: "1.5rem",
          backgroundPosition: "0.5rem center",
        }}
      />
    </div>
  );
}

export default SearchInput;

The above code will render an input element featuring a search icon set as its background with the icon positioned in the middle left section of the input field. Tweak the positioning of the icon by leveraging the background-position property and modify its size using the background-size property.

Answer №2

To start off, make sure to include react-icons in your project setup. To do this with npm, enter the command below into your terminal:

npm install react-icons

After successfully installing react-icons, you can bring in the SearchIcon component within your React component like so:

import { SearchIcon } from 'react-icons';

function MyComponent() {
  return (
    <div>
      <SearchIcon />
      <p>Try clicking the icon for a search</p>
    </div>
  );
}

In this illustration, we are fetching the SearchIcon component from react-icons and utilizing it inside the MyComponent function. Then, we display the icon alongside accompanying text in a div element.

Answer №3

Discover the simplest method for incorporating Icons into your React project with Chakra Ui

/* Easily integrate Chakra UI icons by following this guide */

 import { BellIcon} from '@chakra-ui/icons'
 import { Button } from "@chakra-ui/button"
     /* Alternatively, you can also use this approach */
 return (
     <div>
         <Button aria-label='Notification Icon' icon={<BellIcon />} />
  </div>
 )

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

Using a minus sign to denote negative values and leading zeroes to indicate positive values in regular expressions

I need help with a unique form validation requirement using regex. The values must be integers between -168 and 10688, where negative values range from -168 to -10688. What makes this challenging is that users must include leading zeros, with 4 character ...

What is the process for importing map-obj?

When attempting to incorporate this library, I encountered the following error: /Users/alexs/Documents/projects/xml-controller-test/dist/app.controller.js:20 const map_obj_1 = require("map-obj"); ^ Error [ERR_REQUIRE_ESM]: The u ...

Trouble with Three.js: Obj material not appearing as imported

My main question pertains to the best method of importing 3dsmax models or scenes into three.js, as most existing threads on this topic are several years old. Currently, I have created a simple coke can with a basic texture applied, but I am encountering i ...

The code snippet `document.getElementById("<%= errorIcon.ClientID %>");` is returning a null value

I need to set up validation for both the server and client sides on my registration page. I want a JavaScript function to be called when my TextBox control loses focus (onBlur). Code in the aspx page <div id="nameDiv"> <asp:Upd ...

React - Issue with state not being updated accurately

My current project involves using the <Select> component from Material-ui to create a drop-down menu. I need to update the state of the <Select> component after a selection has been made. To achieve this, I have set the value property of the & ...

Responsive design for iPads and smartphones is essential in ensuring a seamless user

Currently in the process of creating my own personal website, I have been diligently using Chrome Canary to ensure that all my media queries are properly set up. While everything looks great on Canary and functions well in various device modes within the b ...

Creating a scrolling list group in a single column that moves in sync with another longer column

When working with two columns in Bootstrap, such as col-4 and col-8, how can you ensure that a list-group stays fixed within its column and vertically aligned even when the content in the other column is scrolled down? Dealing with this responsively can b ...

How can I utilize module imports with the support of web browsers?

I'm currently troubleshooting why my script tags are not functioning in my html file. I discovered an article mentioning the ability to import modules into browsers using a script tag with a module type. The information was found on this site: https:/ ...

The 'set' property in NextJS does not appear on the 'ReadonlyRequestCookies' type

As I am attempting to establish cookies within the server actions function in Next.js 13.4.1, I came across an issue. You can view an example code for reference. import { cookies } from 'next/headers'; async function create(data) { 'use ...

The functionality of WrapAll is not functioning properly in React JS

$('p').wrapAll($('<div class="wrapper"></div>')); .wrapper { background: #EEE; margin: 10px; padding: 5px; border: 1px solid black; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery. ...

Unique Options to Enhance Your AngularJS Directive

I've been attempting to pass dynamic variables into a directive that showcases a time picker (using pickadate.js: ). However, I'm facing challenges in getting these options into the directive. Despite searching extensively online, I am overwhelme ...

Error in JSON due to the presence of an unexpected token within the

I am facing a challenge with my PHP code, where I take a list of filenames or empty strings and store them in an array. This array is then converted to JSON and saved in a database successfully. However, the problem arises when this array is also stored wi ...

Select a particular checkbox within an HTML table

One of the challenges I'm facing involves working with a HTML table that has a column filled with checkboxes. I'm looking for guidance on how to utilize Javascript to mark a checkbox at a particular row index as checked, without relying on jquery ...

Navigation bar designed to display horizontally

In my React app, I have implemented a navbar using the provided code. It looks great on wide browser windows, but once it goes below the navbar-expand-lg breakpoint, the icons start stacking vertically. How can I prevent this behavior? (refer to the screen ...

Unable to set value for React MUI TextField in React Hook Form Controller inside MUI Stepper Dialog

I am facing an issue with my Button that triggers a MUI Dialog to open. Within the Dialog, there is a MUI Stepper as part of my form which has different required and non-required inputs. //Sample Input <Controller name="stateName" co ...

Executing a forEach loop beginning at a specific index in JavaScript

I am dealing with a large array of items and need to create a paginated list out of them. I am trying to figure out how to initiate a loop, either using forEach or for, at a specific index in the array. For instance, if each page will contain a certain n ...

How to center a big Popover using Twitter Bootstrap for maximum screen coverage

Imagine having a Bootstrap Popover on your website set up like this: HTML: <button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="top" data-content= ...

What is the best way to dynamically update a specific value within an object based on the current state in React/Next?

I have implemented a Context API where an object is set, and when the user clicks, the state changes. I need to update a specific value with the new state value. const initialState = { notification: false, setting: false, profile: false, } exp ...

What are the benefits of using a synchronous XMLHttpRequest?

Many developers opt for asynchronous XMLHttpRequest requests, but the existence of synchronous requests suggests that there could be valid reasons for using them. What might those reasons be? ...

Break down for me what Json is in a way that a five-year-old could understand

Let me clarify one thing, I may not be a Javascript expert but I'm far from being 5 years old. Json is one concept that's been confusing me lately as I dive into the world of programming. Can someone please explain json to me in a simplified mann ...