Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: How to overlay a component on top of another component's element?

I am just starting react. I have a component which has an input field and a button. There is another component which returns JSX (A blinking dot). I am importing the blinking dot component in main component and want to overlay the blinking dot on top of the input field when it is empty.

How can I achieve this? Please help me in this.

The code for this can be found in: https://stackblitz.com/edit/react-xmssdv

function App() {
  const [name, setName] = React.useState("");
  const inputChangeHandler = event => {
    setName(event.target.value);
    console.log(name);
  }

  return (
    <div>
        <input type="text" value={name} onChange={inputChangeHandler} />
      <div className="button">
        <button type="button">Click Me!</button>
      </div>

      <Dot />
    </div>
  );
}
like image 268
newbie Avatar asked Sep 08 '19 19:09

newbie


People also ask

How do you pass props from one component to another?

Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop.

What is Z-Index React?

zIndex is the Expo and React Native analog of CSS's z-index property which lets the developer control the order in which components are displayed over one another.

Can a React component extend another component?

Implement Inheritance in ReactUsing the extends keyword, you can allow the current component to access all the component's properties, including the function, and trigger it from the child component. This example creates one component called ParentClass. jsx. ParentClass extends the component from React as React.


1 Answers

It can be easily achieved by making the following two changes:
step 1. In index.js move the Dot component at the top:

function App() {
  const [name, setName] = React.useState("");
  const [showDot, setShowDot] = React.useState(true);

  React.useEffect(() => {
    name ? setShowDot(false) : setShowDot(true);
  }, [name])

  return (
    <div>
        { showDot ? <Dot /> : null }
        <input type="text" value={name} onChange={() => setName(event.target.value)} />
      <div className="button">
        <button type="button">Click Me!</button>
         { name ? <Dot /> : null }
      </div>


    </div>
  );
}

step 2. In Dot/dot.css introduce the positioning for dot as absolute:

.Blink {
  position: absolute;
  width: 30px;
  height: 30px;
  background-color: blue;
  border-radius: 50%;
  animation: blinker 1s cubic-bezier(0.5, 0, 1, 1) infinite alternate;
}

like image 84
rakesh-ranjan Avatar answered Sep 19 '22 04:09

rakesh-ranjan