I want to change the background image of a site based on the input the user types in. For example, if the user types in New York or New York City or NYC, the background image changes to a picture of NYC.
Right now, I have a div tag with a class and in a CSS file, the background image is set to a url from the internet. I've figured out that you need to import the file that you want to use as a background image if you want to set the inline style in the .jsx file but I think this would be a tedious method since I have hundreds of images that I want to render based on the input. So without using jQuery (I saw another post similar to this question but in jQuery and I've read that using jQuery with React is not a great idea and I'm not even sure I could make it work with my React setup) how would you change the background image of a div depending on an input value?
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>
);
}
CodePudding user response:
You can make use of inline styles of CSS as one of the methods, I've re-written your code below.
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>
);
}
The backgroundImage URL, should be pointing to a particular file/directory in your project that contains the image, or a link to a jpg file that contains the image.
CodePudding user response:
Some websites give API for searching wallpapers and background images that you can use. One of them is Unsplash. Please register as a developer, make an application (or use Demo app) on that, and copy your ACCESS_KEY and past in code (YOUR_ACCESS_KEY) to send your request to Unsplash API and get 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("There is no any word to searching!");
return;
}
setLoading(true);
// Send request to Unsplash API for searching your word and get wallpapers of that.
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 background title</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>
);
}