How to set a React Component or dom element as a background image

12 Aug 2021

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

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

My initial impression on seeing the design was that it would be easy. I thought it’s a image but after exploring the code I came to know that it’s not an image that we have to show as background instead, it’s a React Component. So now what? To solve this problem we need to think from scratch.

Solution:

First, we will think about how to do it and then will implement it step by step.

1. 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 the textarea.

2. Implementation

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


Steps:

1.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.

3.To solve the problem we need to make the textarea background transparent. But then if you click on the React Component you won’t be able to edit the textarea. To solve this set pointer-events: none.

.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
}

4.(Optional) 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



Posted by Ashu Deshwal, Frontend Engineer


blog comments powered by Disqus