Modifying background image in React based on user input value - Here's how!

Is there a way to dynamically change the background image of a website based on user input? I want the background image to update to reflect specific keywords entered by the user. For example, if the user types in "New York", "New York City", or "NYC", then the background image should change to a picture of NYC.

Currently, I have a div element with a designated class, and in my CSS file, the background image is set using a URL from the internet. While I understand that you can import a file to use as a background image inline within a .jsx file, this seems like a cumbersome process, especially since I have numerous images that need to be rendered based on user input. Without relying on jQuery (as it may not integrate well with React), how can I achieve dynamic background image changes for a div based on user input?

function App() {

const [name, setName] = useState('');
const [headingText, setHeadingText] = useState('City');

function handleChange(event){
    setName(event.target.value);
}

function handleKeyDown(event){

  if(event.key === 'Enter'){
      setHeadingText(name);
  }
}

return (
    <div className="App">
        <header className="App-header">

            <input value={name} onKeyDown={handleKeyDown} onChange={handleChange} type="search" placeholder="Search for a city"></input>
        
        </header>
      
    </div>
);
}

Answer №1

If you're looking to add some style directly into your HTML elements, one way is by using inline CSS. I've updated your code below for reference.

function App() {
const [name, setName] = useState('');
const [headingText, setHeadingText] = useState('City');

function handleChange(event){
    setName(event.target.value);
 }
function handleSubmit(event){  
 setHeadingText(name)
  }

return (
    <div className="App" style={{ backgroundImage:`url(${name}.jpg)` }}>
      <header className="App-header">
        <input value={name}  onChange={handleChange} type="search" placeholder="Search for a city"/>
        <button onClick={handleSubmit}>Enter</button>
      </header>
    </div>
      
  );
}

Make sure the URL in the backgroundImage points to an image file within your project directory or provide a link to a .jpg file containing the desired image.

Answer №2

Many platforms provide APIs for accessing a wide range of wallpapers and background images. An example is Unsplash. To utilize this service, it is recommended that you sign up as a developer, create an application (or use the Demo app), and insert your ACCESS_KEY in the code where specified as YOUR_ACCESS_KEY in order to communicate with the Unsplash API and retrieve wallpapers.

import axios from "axios";
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [backgroundUrl, setBackgroundUrl] = useState("");
  const [searchInput, setSearchInput] = useState("");
  const [loading, setLoading] = useState(false);

  const searchBackground = () => {
    if (!searchInput) {
      alert("You have not entered any keyword to search for!");
      return;
    }
    setLoading(true);

    // Sending a request to the Unsplash API to search for the provided keyword and fetch related wallpapers.
    axios
      .get("https://api.unsplash.com/search/photos/", {
        params: {
          client_id: "YOUR_ACCESS_KEY",
          query: searchInput
        }
      })
      .then((res) => {
        const results = res?.data?.results;
        const randomBackground =
          results[Math.floor(Math.random() * results.length)];
        setBackgroundUrl(randomBackground.links.download);
      })
      .catch((err) => {
        console.log(err);
      })
      .then(() => setLoading(false));
  };

  if (loading) return <div>Loading background...</div>;

  return (
    <div className="App">
      <h1>Please enter the title of the background</h1>
      <input
        value={searchInput}
        onChange={(e) => setSearchInput(e.target.value)}
      />
      <button onClick={searchBackground}>Search</button>

      <div style={{ marginTop: 50 }}>
        {backgroundUrl && (
          <img src={backgroundUrl} alt="background" width={"100%"} />
        )}
      </div>
    </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

Develop a feature within a standard plugin that allows users to add, remove, or refresh content easily

I have developed a simple plugin that builds tables: ; (function ($, window, document, undefined) { // Define the plugin name and default options var pluginName = "tableBuilder", defaults = { }; // Plugin constructor func ...

Tips for employing numerous if-else conditions utilizing the ternary operator in jsonpath-plus?

JSON { "customer":{ "address":{ "stateRegion":"", "stateRegionCode":"" } } } Code "address.state_code": "$.customer.address.[stateRegion ? state ...

Reviving form data after component unmounts

Within my React Router setup, there is a form mounted as a route that acts as the main page. This form includes buttons leading to different routes, each with a back button that returns to the main form. The issue arises when using 'redux-form' b ...

Media query failing to activate

As I delve into utilizing media queries to adjust background images and hide content within a division tag when the screen size exceeds 640px, I'm encountering issues with the functionality. Being new to this concept, I can't shake off the feelin ...

What is the best way to align my content alongside my sidebar?

I am facing some challenges with my website layout because I used Bootstrap to integrate a sidebar. The sidebar has caused issues with the positioning of my content, and I'm struggling to align it properly next to the sidebar on the left side. Please ...

Using Selenium to interact with drop-down lists using div tags instead of select tags

As a newcomer to automated testing using Selenium Web Driver, I am struggling to test drop down lists for the location type without relying on the select command. The element in question is enclosed within a div tag. I attempted sending keys but that meth ...

A duo of adjacent buttons styled with HTML, CSS, and Bootstrap

I'm encountering an issue with the layout of my design. On my product page, I have two buttons placed on top of each other because one is within a form (refer to the image). https://i.sstatic.net/cS9TI.jpg I would like to position the two buttons s ...

Halfway opening the dialog drawer

My goal is to create a dialog box that opens up in the lower half of the blue area when a specific button is clicked, while the upper half displays a backdrop. However, I have been facing issues with making the dialog box appear only in the designated area ...

What steps do I need to take to transform this click event function into one that is triggered automatically upon the div loading?

In order to automatically load content into a div using innerHTML, the PHP file must be retrieved and the div updated with its content. Within this div is another one labeled "tweet" which displays actual tweets based on a specific hashtag provided through ...

Generate a new subprocess and terminate it once the operation has been initiated

Using child processes in the following way: var exec = require('child_process').exec; var cmd = 'npm install async --save'; exec(cmd, function(error, stdout, stderr) { console.log('stdout: ' + stdout); ...

retrieveSourceData(), postmodification of Handsontable with Vue

How can I use getSourceData() after a change event in Vue? I need to access the instance of Handsontable, but I'm not sure how to do that in Vue. Essentially, I need to retrieve all rows that have been edited. For example: const my_instance = this.$ ...

Develop an event listener in a React Component that watches for changes

I have a React component and I am looking to implement an "onChange" event that can be detected by another component in the application. const FirstComponent = () => { // Implement functionality // How can I create an event here that can be detec ...

Refresh the calendar to retrieve updated information

Utilizing the "events" elements of fullcalendar to retrieve data dynamically has been successful so far and I am satisfied with it. However, I am facing a challenge in passing a GET/POST parameter to the PHP page and refreshing the call to incorporate the ...

Modifying CSS styles in real-time according to the present data

Is there a way to dynamically change CSS values based on current CSS values? For example, instead of explicitly setting different values like this: .test{ margin-top:100px; } .test:hover{ margin-top:90px; } Is it possible to achieve the same eff ...

What is the best way to confine a child div with a dynamic height?

Upon initialization of Jwplayer, a class is injected with the following CSS: .jwplayer.jw-flag-aspect-mode { height: auto !important; } Here's my code snippet: <div style="height: 80vh; width: 100%"> <div style="height: 90%; width: 100 ...

Beginner experiencing website overflow problem

After completing a basic web development course, I decided to create my first homepage. While I am satisfied with how it looks on a PC or laptop, the layout gets messy on mobile devices. I tried using <meta name="viewport" content="width= ...

Feeling lost on how to utilize .map, .reduce, or foreach in my code

Recently delving into JavaScript, I find myself a bit perplexed despite scouring through various answers and resources on Mozilla.org. My struggle lies in seamlessly using .map and .filter on straightforward arrays, but feeling a bit lost when it comes to ...

Hover effect not activating on image within modal

only img:hover is working, but after adding this to the CSS: #user-profile #user-myModal .modal-body img:hover #user-profile #user-myModal .modal-body .change-pic i{ display: block; } it's not working. I changed the class and id names, tried eve ...

Tips for moving a title sideways and adjusting the bottom section by x pixels

I am seeking to accomplish a design similar to this using CSS in order to create a title of <h1>DISCOVER <span>WEB 3</span> DIMENSIONS</h1>. How do you recommend achieving this? Thank you, I have searched on Google and asked frie ...

The primary text in the MUI ListItem exceeds the secondary action of the ListItem

I am currently using MUI (v5) List component. My list is quite simple, with each item having text on the left and a value on the right. The issue arises when the list's width shrinks as the window size decreases. The text on the left (<ListItemTe ...