Show a pop-up form when a user focuses on it using React

Hello, I have been looking for a way to create an overlay with a form that appears when a specific input field is clicked. I am trying to achieve this using React. Can someone please advise me on how to accomplish this?

Here is my code

import React, { Component } from 'react';


class Middle extends Component {

    constructor(props) {
        super(props);
        this.state = {
            posts: []
        }
    }

    render() {

        function displayOverlay(e) {
            e.preventDefault();
            alert("Now the overlay should appear");
        }

        return (
            <div className="middle_div">

                <input className='post_data_input' placeholder="Ask your question here" ref="postTxt"
                       onClick={displayOverlay}/>

            </div>


        );
    }
}

export default Middle;

I have created a function that triggers an alert when the input field is clicked. Instead of the alert, I would like to show a transparent overlay with a form.

I am aiming for something similar to this example:

http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_overlay

Thank you in advance.

Answer №1

Here's the code snippet to dynamically change the className of the side bar. By calling toggleSideBar, the className will switch between hideSideBar and showSideBar. Make sure to write the CSS for these classes as shown in the code school link. Hopefully, it should work smoothly.

import React, { Component } from 'react';


class Middle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sidebar: 'hideSideBar',
      posts: [],
    }
  }

  toggleSideBar() {
    if(this.state.toggleBar === 'showSideBar') {
      this.setState({ toggleBar: 'hideSideBar' });
    } else {
      this.setState({ toggleBar: 'showSideBar' });        
    }
  }

  render() {
    return (
      <div className="middle_div">
        <input
          className='post_data_input'
          placeholder="Ask your question here"
          ref="postTxt"
          onClick={this.toggleSideBar.bind(this)}
        />

        <div className={this.state.sidebar} />
          // This will be the sidebar
        </div>
      </div>
    );
  }
}

export default Middle;

Answer №2

I have customized a React component based on the link provided in your question. I believe this can assist you in achieving some of your desired functionality.

class Test extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            style : {
                width : 350
            }
        };
        this.openNav = this.openNav.bind(this);
        this.closeNav = this.closeNav.bind(this);
    }

    componentDidMount() {
        document.addEventListener("click", this.closeNav);
    }

    componentWillUnmount() {
        document.removeEventListener("click", this.closeNav);
    }

    openNav() {
        const style = { width : 350 };
        this.setState({ style });
        document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
        document.addEventListener("click", this.closeNav);
    }

    closeNav() {
        document.removeEventListener("click", this.closeNav);
        const style = { width : 0 };
        this.setState({ style });
        document.body.style.backgroundColor = "#F3F3F3";
    }

    render() {
        return (
          <div>
          <h2>Fullscreen Overlay Nav Example</h2>
<p>Click on the element below to open the fullscreen overlay navigation menu.</p>
<p>In this example, the navigation menu will slide in, from left to right:</p>
<span style={{fontSize:30,cursor:"pointer"}} onClick={this.openNav}>&#9776; open</span>
            <div
                ref       = "snav"
                className = "overlay"
                style     = {this.state.style}
            >
                <div className = "sidenav-container">
                    <div className = "text-center">
                      <h2>Form</h2>
                      <p>This is a sample input form</p>
                    </div>
                    <a
                        href      = "javascript:void(0)"
                        className = "closebtn"
                        onClick   = {this.closeNav}
                    >
                        ×
                    </a>
                  <div className = "list-group">
                      {/*your form component goes here */}
                      {this.props.children}
                  </div>
                </div>
            </div>
          </div>
        );
    }
}

ReactDOM.render(
  <Test/>,
  document.getElementById('test')
);
.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0, 0.9);
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

@media screen and (max-height: 450px) {
  .overlay a {font-size: 20px}
  .overlay .closebtn {
    font-size: 40px;
    top: 15px;
    right: 35px;
  }
}

.overlay h2, .overlay p {
  color:white;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id="test"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the values of "qty" and "price" and access them within the item [array] without knowing the IDs?

I am currently working on a shopping cart project, specifically on the "previous orders" page to display order details. My goal is to output this information in an (.ejs) file. The data structure includes nested objects, and within one object, propertie ...

Techniques for dynamically displaying or hiding elements depending on various input groups using jQuery?

I am faced with a challenging task of handling multiple product forms on a single page. Each form contains various color options represented by radio buttons, each marked with either an available or unavailable attribute. My goal is to display a customize ...

When the open button is clicked, the Div will toggle between open and closed states

Recently, some of my questions have not been well-received, which makes me feel a bit disheartened. It's important to remember to be kind when providing feedback. I've noticed that some people downvote without offering constructive criticism, whi ...

The CSS overlay effect refuses to shut down

Greetings everyone, I'm new around here so please bear with me. I am encountering an issue wherein the overlay only works in one direction - it appears when the button is clicked, but nothing happens when attempting to close it. I have tried adjustin ...

Transmitting video through a local area network

I am seeking a solution to stream video content to a local network with potentially over 1000 viewers. The streaming will need to be accessible via web browsers such as Internet Explorer, Chrome, and Firefox, as not all users have internet access due to co ...

The element's position remains unchanged after the .click re-event in the function

Welcome to my first attempt at using jQuery! Please bear with me as I navigate through this learning process. Here's the challenge: I have a series of elements in my HTML. <div class="garden"> <div class="point left">&#9668;</d ...

Utilizing React.js with Material-UI to retrieve data from a table row when clicked

I came across a code snippet for a material table that can handle lists as input and perform pagination, sorting, and filtering on them. The challenge I am facing is figuring out how to extract the data from a row click event and navigate to a new route al ...

Add a touch of shadow to a stationary top banner as you scroll through the page

Is there a way to gradually fade in a shadow while scrolling, so that the shadow only reaches an opacity of 0.5 after scrolling a certain number of pixels? I've come across solutions to add a shadow or class to the top banner based on content position ...

Center Align Images in HTML List Items

Hey there! I'm currently diving into the world of web development with responsive design, but I'm still a bit of a newbie. So please bear with me as I try to explain my issue in detail. If you need more information, just let me know! My current ...

Storing data locally in PhoneGap using localStorage via AJAX calls is a common requirement for

Our mobile application is built with cordova [phonegap] and we are looking to implement offline saving of results into the cache memory. The results are fetched from a PHP server and displayed in a webview using ajax and javascript. I have tried using loc ...

Resetting a password using email feature in React

After using the react app, I realized that I need to include a reset-password email functionality in my project. Currently, I am stuck on the react forget password page and here is an excerpt of my code: import React, {useEffect, useRef, useState} from & ...

Timepicker Bootstrapping

I've been searching for a time picker widget that works well with Bootstrap styling. The jdewit widget has a great style, but unfortunately it comes with a lot of bugs. I'm on a tight deadline for my project and don't have the time to deal w ...

Looking for a way to verify and match passwords in React Hook Form? Wondering if there's a built-in validation feature to display error messages with React Hook Form?

Having trouble validating the password and confirm the password in my form. Is there a specific property in useForm for this purpose in the latest version of react hook form? Any help would be appreciated. import React, { useState } from 'react' ...

A step-by-step guide on retrieving a value from a DateTime picker in a React application

I am utilizing Material-UI to create a DateTime picker. You can check out my demo code here. In order to observe the current selected value, I have added console.log to the function handleChange. However, I am facing an issue where the value does not chan ...

Is it possible to utilize React.lazy within a function?

Is there a way to dynamically lazy load a component in a more general manner, such as within a function? For example: function lazyLoadComponent() { if (/* condition */) { return React.lazy(async () => { const module = await import('ma ...

Flex box causing Bootstrap5 responsive table to overflow

Need help with fixing overflow issue in a fixed-width div used as a left sidebar. The main content renders correctly except for tables with many columns, causing overflow before the scroll bar appears. How can this be resolved? Various layout attempts hav ...

How can you retrieve the id of a div element using an if/else statement in React Js?

In my React Js project, I am attempting to create a responsive connecting line between 3 divs. While successfully adding a line between the elements, I encountered an issue when using Axios to fetch data and display it with an if/else statement. The error ...

Tips for showcasing five inputs in a single row on a webpage using a customized width in Bootstrap

I am struggling to align 5 inputs in a single row on a page with custom widths. For example, I want the amount input to be smaller than the offer input. I attempted to use columns and apply different classes for size, but the submit button ended up not bei ...

Changing the constant value

While browsing through an interesting article, I came across a fascinating CodePen. What caught my attention was the use of const in the increment method to set count. It got me thinking - how can you override a constant value? Can someone please explain t ...

Tips for utilizing a prop to generate a unique image URL

I am struggling with incorporating the prop into the file name in order to use it as part of the src attribute for an image. It seems like I am missing something crucial in my approach. What I'm trying to do is pass on the name as a string and then u ...