CSS hack: How to set a React Component or dom element as a background image. Ashu Deshwal Follow Apr 19 · 2 min read

At my internship at HackerEarth, I faced an interesting problem. This blog is about that and how I solved.

Problem: To set a background image to the textarea element.

By looking into the design I thought it will be gonna easy but after exploring the code I came to know that we don’t have that image which we want to show but actually that was a React Component we made. So now what? To solve this problem we need to think from scratch.

It’s time to hack….

Solution:

First, we will think from scratch and then step by step we will gonna implement.

Think From Scratch

In this example, as you can see the content in the body element overlap the background-image. To solve this problem we just need to overlap the React Component with textarea.

2. Implementation

Create a textarea and React Component which we are gonna going to use. In the left is textarea and in right is the React Component which we are going to set as a background image to textarea element.

Steps:

Create a div which wrap textarea and React Component. Set the div position: relative and React Component position: absolute, top: 0 & left: 0.

<div className="editor-container"> // position: relative <textarea className="editor" /> <BackGround /> // position: absolute; top: 0; left: 0; </div>

2. To overlap textarea on React component we need to set React Component z-index: -1.

.bg-img {

position: absolute;

top: 0;

left: 0;

width: 250px;

font-family: monospace;

text-align: center;

color: rgba(0, 0, 0, 0.29);

z-index: -1;

}

As you can see we have a problem now:

React Component is below the textarea and we are not able to see.

2. To solve the problem we need to make the textarea background transparent. Now if you see when we click on React Component we are not able to edit textarea. To solve this set React Component pointer-events: none to avoid pointer events.

.editor {

height: 400px;

width: 400px;

background: rgba(0, 0, 0, 0); // background transparent

} .bg-img {

position: absolute;

top: 0;

left: 0;

width: 250px;

font-family: monospace;

text-align: center;

color: rgba(0, 0, 0, 0.29);

z-index: -1;

pointer-events: none; // not to react on pointer events

}

3.(Optional step) Set the position of React Component at the centre.

.bg-img {

position: absolute;

width: 250px;

font-family: monospace;

text-align: center;

color: rgba(0, 0, 0, 0.29);

z-index: -1;

pointer-events: none;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

}

End Result