In this tutorial, we will see how to use background image in react js with tailwind css. We will see background image examples with Tailwind CSS & React.
Tool Use
React JS
Tailwind CSS 3.v
First you need to setup react project with tailwind css. You can install manually or you read below blog.
How to install Tailwind CSS in React
Install & Setup Vite + React + Typescript + Tailwind CSS 3
Example 1
React with tailwind css background image using inline style.
export default function Images() {
return (
<>
<div className="flex justify-center items-center h-screen">
<div
className="bg-cover bg-center h-80 w-96"
style={{
backgroundImage:
"url('https://cdn.pixabay.com/photo/2023/01/23/09/26/cat-7738210__340.jpg')",
}}
></div>
</div>
</>
);
}
You can also use by define image variable it is much better to read.
export default function Images() {
const imageURL = "https://cdn.pixabay.com/photo/2023/01/23/09/26/cat-7738210__340.jpg";
return (
<>
<div className="flex justify-center items-center h-screen">
<div
className="bg-cover bg-center h-80 w-96"
style={{
backgroundImage: `url(${imageURL})`,
}}
></div>
</div>
</>
);
}
Example 2
You can use background image in react using tailwind bg-url.
export default function Images() {
return (
<>
<div className="flex justify-center items-center h-screen">
<div className='bg-[url("https://cdn.pixabay.com/photo/2023/01/23/09/26/cat-7738210__340.jpg")] bg-cover bg-center h-80 w-96'></div>
</div>
</>
);
}