Navbar triggering a popup window on click event

I'm working on a social media project with React on Rails and I have a NavBar component that manages the routing for each link. There's a link called Ventbox, similar to Twitter's Tweetbox, but instead of navigating to a new page at '/vent', I want it to pop up on the current page with the same endpoint. How can I modify my code to achieve this?

This is what my NavBar component looks like:

import React from 'react'
import { NavLink } from "react-router-dom";
import { navData } from "./navData.js";
import styles from "./styles/navbar.module.css";
import { useState } from "react";
import KeyboardDoubleArrowRightIcon from '@mui/icons-material/KeyboardDoubleArrowRight';
import KeyboardDoubleArrowLeftIcon from '@mui/icons-material/KeyboardDoubleArrowLeft';
import Ventbox from './Ventbox'
import CreateIcon from '@mui/icons-material/Create';

export default function NavBar() {

  const [open, setopen] = useState(false)
  
  

    const toggleOpen = () => {
        setopen(!open)
    }
  

    return (
      
      <div className={open?styles.sidenav:styles.sidenavClosed}>
          <button className={styles.menuBtn} onClick={toggleOpen}>
              {open? <KeyboardDoubleArrowLeftIcon />: <KeyboardDoubleArrowRightIcon />}
              </button>
          {navData.map(item =>{
            return <NavLink key={item.id} className={styles.sideitem} to={item.link}>
              {item.icon}
              <span className={styles.linkText}>{item.text}</span>
          </NavLink>
          })}
              <NavLink key={'ventbox'} className={styles.sideitem} to="/vent">
                <CreateIcon />
                <Ventbox to="/vent" style={styles.linkText} />
              </NavLink>
      </div>
    )
  }

And here's my Ventbox component:

import React, { useState } from "react";
import './styles/Ventbox.css'
import {useNavigate} from 'react-router-dom'


function Ventbox({style}) {
    
    const [popup,setPop] = useState(false);
    const [content, setContent] = useState("");
    const [textLimit, setTextLimit] = useState(250);
    

    const handleClickOpen = () => {
        setPop(!popup);
    }

    const closePopup = () => {
        setPop(false);
    }

    const handleChange = e => {
        setContent(e.target.value);
        setTextLimit(250 - e.target.value.length);
    }

    const handleSubmit = async e => {
        e.preventDefault();
        if (content.length > 250) {
            alert("Text limit reached");
        } else {
            try {
                const response = await fetch(`/posts`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ content: content })
                });
                const data = await response.json();
                console.log(data);
                
            } catch (error) {
                console.error(error);
            }
        }
    }

    return(
        <div>
            <span onClick={handleClickOpen} className={style}>Vent</span>
            <div>
                {
                    popup?
                    <div className="main">
                        <div className="popup">
                            <div className="popup-header">
                                <h1>What's on your mind?</h1>
                                <button className="delete-button" onClick={closePopup}>X</button>
                            </div>
                            <div>
                                <form onSubmit={handleSubmit}>
                                    <input className="textbox" placeholder="Enter text here" 
                                        value={content} 
                                        onChange={handleChange} 
                                        maxLength={250} 
                                    />
                                    <p>Characters remaining: {textLimit}</p>
                                    <button className="post-button"type="submit">Post</button>
                                </form>
                            </div>
                        </div>
                    </div>:""
                }
            </div>
        </div>
    )
}
export default Ventbox;

Lastly, here are the Icons and routes in my navData component:

import HomeIcon from '@mui/icons-material/Home';
import InfoIcon from '@mui/icons-material/Info';
import MenuBookIcon from '@mui/icons-material/MenuBook'; 
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import HowToRegIcon from '@mui/icons-material/HowToReg';
import VerifiedUserIcon from '@mui/icons-material/VerifiedUser';

import SendIcon from '@mui/icons-material/Send';
import NotificationsIcon from '@mui/icons-material/Notifications';
import CreateIcon from '@mui/icons-material/Create';
import Ventbox from './Ventbox'
import Popup from 'reactjs-popup'
import {useState} from 'react'


export const navData = [
    
    {
        id: 0,
        icon: <HomeIcon/>,
        text: "Home",
        link: "/"
    },
    {
        id: 1,
        icon: <AccountCircleIcon/>,
        text: "Profile",
        link: "/profile"
    },
    {
        id: 2,
        icon: <SendIcon/>,
        text: "Messages",
        link: "/messages"
    },
    {
        id: 3,
        icon: <NotificationsIcon/>,
        text: "Notifications",
        link: "/notifications"
    },

    {
        id: 5,
        icon: <HowToRegIcon/>,
        text: "Signup/Login",
        link: "/signin"
    },
]

If anyone could provide some guidance, it would be greatly appreciated!

I've tried various approaches but I seem to be stuck :(

Answer №1

When utilizing the mui library, one potential solution is to encapsulate your component within a Modal element.

Visit this link for more information on Material-UI Modals

<CreateIcon onClick={handleOpen}/>
<Modal
  open={open}
  onClose={handleClose}
  aria-labelledby="modal-modal-title"
  aria-describedby="modal-modal-description"
>
  <Ventbox style={styles.linkText} />
</Modal>

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 process for adding an item to the dictionary state?

I'm currently working on a function to push an object to the state in my code. The goal of this function is to duplicate the first state object and append it to the end of the state array. addField() { const index = (this.state?.fields.length) -1 ...

What causes overflow-x scroll to prevent scrolling to the left unless the initial scroll is to the left?

<div class="row justify-content-center mob-view" > <div class="col-lg-3 col-md-4" *ngFor="let slide of specialization"> <div class="brower-box"> &l ...

Exploring ways to access the children elements of React components for the purpose of incorporating wrapper components

I am working with a layout component called GridLayout that accepts a react component named WidgetsList. The function of this component is to return a list of components. My goal is to wrap each child node of the WidgetsList component in a wrapper compone ...

Getting the desired value from a CreatableSelect in React can be achieved by following these steps:

I have a form that includes a React library component called React Select. I'm struggling to retrieve the target value of this input field. Here's my code snippet: # CreatableSelect tag <CreatableSelect className={Astyle.selectInput} i ...

Core MVC - Adjusting Font Size

After setting up an MVC Core App with automatic scaffolding, I am now faced with the challenge of adjusting the font size in my html View. The question is: How can I change the font size in bootstrap.css? There seem to be multiple font sizes available an ...

Image not showing correctly after closing the bootstrap modal

I am currently working on creating a gallery with hover effects for each image, similar to the one found here. My goal is to have a Bootstrap modal open when I click on a link within the hovered image, displaying additional content. Everything seems to be ...

What is the trick to concealing a div on a webpage through the addition of a designated parameter to the URL?

As a newbie blogger delving into the world of HTML, my knowledge of JavaScript is quite limited. I am eager to find out how I can hide any div on a webpage simply by adding a parameter to the URL; for example, if I were to add ?hide=header-wrapper at the e ...

Can the custom scrollbar CSS property of a DOM node be located using JavaScript?

Is it possible to find a CSS property of a pseudo-class (like scrollbar pseudoclasses in Chrome) for an element styled with it? Here's an example: <body><div #a></div></body> <style> #a::-webkit-scrollbar { width: ...

eslint alert: The aria-current attribute must have a value that is a single token from the following list: page, step, location, date, time, true

<div role="button" tabIndex="0" className="nav-link pad-0-r" aria-current={'${selectedTab === item ? 'page' : 'false'}'} onClick={()=> onClick(item)} onKeyDown= ...

Utilizing a Function's Return Value as a State in React - A Comprehensive Guide

Currently, I am delving into the realm of functional components within React and have crafted a simple piece of code that should output 'Nah' if the state value is at 0. However, there seems to be an issue as this functionality does not seem to ...

Bootstrap 5 - centering "padding" both internally and externally within the accordion

Need help aligning three Boostrap 5 grids: Header outside of accordion Overview in accordion header Details in accordion body The accordion header has margins and padding on the left and right, and the collapse icon also occupies some space. I want the ...

Using Axios with Mongoose to Update Documents in Not Working State

I'm currently working on implementing an edit feature for updating posts. My goal is to initially update a specific post by its ID and then make it more dynamic. Although I am able to successfully send a PUT request using axios, I'm not getting ...

Issue with Tailwind CSS: The 'overflow-y' property does not scroll all the way to the bottom when using 'top-[63px]'

I'm facing an issue with my Tailwind CSS code that is hindering me from scrolling to the bottom of an aside element. <body> <div> <nav class=" bg-white px-2 py-2.5 dark:bg-gray-800 sm:px-4 fixed w-full z-20 border-b borde ...

What are the potential reasons for a function in React not being identified as a function?

I recently started learning React and decided to follow this YouTube tutorial on creating a TO DO LIST using React. https://www.youtube.com/watch?v=E1E08i2UJGI Everything seems to be in place, but when I try to interact with my form by typing something an ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

Utilizing Material-UI Data Grid's onSelectionChange Prop with a React Hook

Encountering an issue when attempting to send selected rows from a Material-UI data-grid component to a React Hook, resulting in the site crashing with this error message: Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

On the server side, an error status of 400 is encountered, while the client side shows a successful status code of 200

I have encountered an issue with my login authentication system. I have set up the logic to redirect users to the home page upon successful login and back to the login page if the username is incorrect. The status codes 200 and 400 are being checked for th ...

What can be achieved with the use of '###' in flexdashboard/rmarkdown?

My flexdashboard is divided into multiple sections separated by the '###' heading, as shown below: page 1 ===================================== Column ----------------------------------------------------------------------- ### section 1 bla ...

Keep track of e.target as the input in React is modified

I am struggling with formatting an input field and highlighting its text when focused. After updating the state, the event does not trigger as expected. I see why this is happening, but I am unsure how to highlight the text of the input after the change. ...

Using only HTML and CSS, part of the text should transition in a Carousel without the use of JavaScript or jQuery

Looking to create a Carousel with changing text at a fixed interval, focusing on topics like mobile IoT application development and transport products. Currently utilizing the Aurelia framework. $('#carouselExampleSlidesOnly').carousel({ int ...