How to set a React Component or dom element as a background image
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.
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.
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.
1.Create a div which wrap textarea and React Component. Set the div position: relative and React Component position: absolute, top: 0 & left: 0.
2.To overlap textarea on React component we need to set React Component 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.
4.(Optional) Set the position of React Component at the centre.
Posted by Ashu Deshwal, Frontend Engineer