`We enhance collaboration within sibling next components by exchanging information`

Completely new to web development, I have been working on an app with a navbar that allows users to select items from a drop-down menu. My specific issue is trying to access the title.id in a sibling component, but it keeps coming up as null.

PARENT COMPONENT:


import Popup from 'reactjs-popup';
import Navbar from '../../components/navbar.js'
import {AddQuestion, TitleDescription} from '../../components/discussionPage_styles.js'
import { TitleOutlined } from '@mui/icons-material';
import {update} from "../../components/discussionfunctions.js"
import DiscussionPage  from '../../components/discussionPage.js';
import React, { useState } from "react";

const discussions = () => {
  const [selectedTitleId, setSelectedTitleId] = useState(null);

  const handleTitleSelect = (titleId) => {
    setSelectedTitleId(titleId);
  };

  return (
    <>
      <Navbar handleTitleSelect={handleTitleSelect} />
      <DiscussionPage selectedId={selectedTitleId} />
    </>
  );
};

export default discussions;

SIBLING 1;

import React, { useEffect, useState } from "react";
import DotsVertical from '@mui/icons-material/MoreVert';
import ArrowDropDown from '@mui/icons-material/ArrowDropDown';
import People from '@mui/icons-material/People';
import { fetchDiscussions } from './discussionfunctions.js';
import {IconContext} from "react-icons";
import 
{
    DiscussionDropdownContainer,
    DiscussionDropdownMenu,
    DropdownContainer,
    DropdownButton,
    DropdownLink,
    DropdownMenu,
    DropdownMenuItem,
    Nav,
    NavbarContainer,
    Menu,
    MenuLink,
    MenuItem,
    closeMenu,
    IconButton,
} from './navbar_styles';
import DiscussionPage from "../pages/dashboard/discussions.js";

const Navbar = ({handleTitleSelect}) => {
  const [click, setClick] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [titles, setTitles] = useState([]);
  const [isTitleOpen, setIsTitleOpen] = useState(false);
  
  const handleMenuToggle = () => {
    setClick(!click);
  };

  //dropdown state
  const handleDropdownToggle = () => {
    setIsOpen(!isOpen);
  };

  const handleTitleToggle = () => {
    setIsTitleOpen(!isTitleOpen);
  }

  //save current titleId
  const handleTitleSelectNav = (titleId) => {
    handleTitleSelect(titleId);
  }


  const handleLogout = () => {
    // handle logout logic here
  };
  //grab all the titles from the discussiondata.json

  useEffect(() => {
    extractTitles();
  }, []);

  const extractTitles = async () => {
    const discussions = await fetchDiscussions();
  
    if (!discussions) {
      console.error('No discussions found');
      return;
    }
  
    const titles = discussions.map(discussion => ({
      id: discussion.id,
      name: discussion.name,
    }));
  
    setTitles(titles);
  }

  return (
    <div>
      <IconContext.Provider value={{ color: '#fff'}}> 
        <Nav>
          <NavbarContainer>
          <DiscussionDropdownContainer>
              <DropdownButton onClick={handleTitleToggle}>
                <ArrowDropDown />
              </DropdownButton>
              {isTitleOpen && (
                <DiscussionDropdownMenu>
                  {titles.map(title => (
                    <DropdownMenuItem key={title.id}>
                      <DropdownLink onClick={() => handleTitleSelectNav(title.id)} href={`/dashboard/discussions`}>{title.name}</DropdownLink>
                    </DropdownMenuItem>
                  ))}
                </DiscussionDropdownMenu>
              )}
            </DiscussionDropdownContainer>
            <Menu onClick={handleMenuToggle} click={click}>
              <MenuItem>
                <MenuLink onClick={closeMenu} href="/dashboard/discussions">Discussions</MenuLink>
              </MenuItem>
              <MenuItem>
                <MenuLink onClick={closeMenu} href="/responses">Responses</MenuLink>
              </MenuItem>
              <MenuItem>
                <MenuLink onClick={closeMenu} href="/insights">Insights</MenuLink>
              </MenuItem>
            </Menu>
            <DropdownContainer>
                <DropdownButton onClick={handleDropdownToggle}>
                  <DotsVertical />
                </DropdownButton>
                {isOpen && (
                  <DropdownMenu>
                    <DropdownMenuItem>
                        <DropdownLink onClick={closeMenu} href="/settings">Settings</DropdownLink>
                    </DropdownMenuItem>
                    <DropdownMenuItem>
                        <DropdownLink onClick={closeMenu} href="/">Log Out</DropdownLink>
                    </DropdownMenuItem>
                  </DropdownMenu>
                )}
              </DropdownContainer>
                <IconButton>
                    <People />
                </IconButton>
          </NavbarContainer>
        </Nav>
      </IconContext.Provider>
    </div>
  );
}

export default Navbar;

SIBLING 2:


import Navbar from './navbar.js'
import {AddQuestion, TitleDescription} from './discussionPage_styles.js'
import {update} from "./discussionfunctions.js"
 

const DiscussionPage = ({ selectedId }) => {

    console.log("Selected Title ID: ", selectedId);

    return (
        <div>
            <TitleDescription action="something" method="post" >
                <label for="first">{selectedId}</label>
                <input type="text" id="first" name="first" />
                <label for="last">Description</label>
                <input type="text" id="last" name="last" />
                <button type="submit">Submit</button>
            </TitleDescription>
            <AddQuestion src="../plus-circle.svg"/>
        </div>
    )
}

export default DiscussionPage

I've attempted using chatgpt and other methods to retrieve that data without success, looking for serious assistance.

Answer №1

In theory, this approach should be effective. One option is to pass the setSelectedTitleId method directly to the initial sibling.

Additionally, it's important to confirm if fetchDiscussions is retrieving accurate values and that title.id is not undefined.

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

Using Higher Order Components in React with TypeScript to pass a component as a prop

Exploring the steps outlined in this guide: https://reacttraining.com/react-router/web/example/auth-workflow. Attempting to replicate the code: const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props = ...

Can someone show me the method to retrieve the book title based on a particular ID using linqjs?

I am working with a JavaScript array that contains objects including an id and book title. My goal is to search this array and retrieve the title based on a given id, preferably using linqjs. For example: "213-46-8915" : id "The Busy Executive's ...

I am looking to trigger the change event from within the click event in Angular

My objective involves detecting when the cancel button is clicked while a file is being uploaded. I am trying to accomplish this by triggering the click event, then monitoring for the change event. If the change event occurs, the document will be uploaded. ...

Upgrading to Bootstrap 5 and customizing the collapse button text upon click

I've spent a lot of time searching for a solution to my problem, but all the advice I found is for bootstrap 3 and 4, not version 5. Below is the code I am currently using: <div class="p-3">9 Members Online <a class="p-1 btn ...

response cannot be generated outside of the db.query function

router.get('/details/(:id)', (req, res) => { let vehicle_base; db.query("select b.name, count(b.name) AS total_vehicles from base AS b, vehicle AS v where b.id = v.base_id AND b.fleet_id = " + req.params.id , function(err, result){ ...

Having issues with email verification and the length of phone numbers not functioning properly

I need to validate two text fields before registration: the email must be in correct format and the number must have exactly 11 digits. Any mismatches should trigger an error message. For the email validation, I used a function that checks for the require ...

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

Execute PHP code upon JavaScript confirmation

Whenever I update the status, an email is automatically sent. The issue is that it sends the email again if any other field is updated as well. What I want is a confirmation prompt before sending the email. I tried using AJAX to handle this, but even thoug ...

The supertest request body cannot be found

Testing my express server POST endpoint using supertest has been a challenge for me. Although everything works perfectly in postman, I encountered an issue when trying to pass body parameters into the test. It seems like the body parameters are not being p ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

Checkbox input with alphabetical ordering

I am currently facing an issue with a form that has checkboxes, but the text is not in alphabetical order. While there are plenty of examples for lists, finding examples for checkboxes has been challenging. http://jsfiddle.net/fG9qm/ <form> < ...

Can cucumber steps be executed conditionally within a single scenario?

I would like to streamline my testing process by using one feature file for both desktop and mobile tests. I am looking to run two separate tests, with one tagged as @mobile and the other as @desktop. By doing this, I can avoid creating a duplicate feature ...

What is the reasoning behind jQuery UI employing CSS classes as opposed to pseudo-classes?

In this detailed explanation found on this website, it is discussed why jQuery UI uses CSS classes like .ui-state-active that are applied through JavaScript, rather than utilizing existing CSS pseudo-classes like :active. What is the reasoning behind thi ...

What is the process for completing a form and then going back to edit the data in PHP?

I am having trouble filling out a form and then being able to make changes to the entries later. However, every time I go back to modify the records, I want the form to still have the previous values intact. Unfortunately, when I tried putting " /> An ...

Struggling to efficiently handle imported JSON data using VUE.JS JavaScript?

Struggling to extract specific information from JSON data that I need to import. Here is the sample data I'm working with: I am trying to extract details like the name, description, and professor for each entry. This is how I'm importing the d ...

Creating a 404 Error Response in Express.js

Inside app.js, I currently have the following code: // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); This code executes when a non-existent URL ...

Apollo Client is not properly sending non-server-side rendered requests in conjunction with Next.js

I'm facing a challenge where only server-side requests are being transmitted by the Apollo Client. As far as I know, there should be a client created during initialization in the _app file for non-SSR requests, and another when an SSR request is requi ...

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...

Encountering a CORS policy issue while attempting to retrieve data from an API

I have been attempting to retrieve data from the DHL API, however, I keep encountering issues due to CORS policy blocking the request. Even though I have configured the CORS policy on my backend server, the error persists. What could be the issue? Here ...

Utilize Ajax datatable to showcase information in a visually interactive format

I've been grappling with this problem for an entire day. Essentially, I have a table and I need to pass data in a multidimensional array $list through a datatable using AJAX. This way, I can JSON encode it and send it back for display: $('#table ...