Guide on how to pass the chosen dropdown value from a custom component back to the main component

I've developed a customized MUI select component in React and have integrated it multiple times within another component as shown:

customDropdown.js


import * as React from 'react';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import Chip from '@mui/material/Chip';
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import ArrowCircleUpIcon from '@mui/icons-material/ArrowCircleUp';
import ArrowCircleDownIcon from '@mui/icons-material/ArrowCircleDown';
import { useLocation } from 'react-router-dom';

export default function CustomDropdown({ inputLabelId, dropdownId, dropdownValue1, dropdownLabel }) {
    const [dropdownValue, setDropDownValue] = React.useState('');
    const location = useLocation();

    const handleChange = (event) => { 
        setDropDownValue(event.target.value);  
    };

    React.useEffect(() => {
        setDropDownValue(dropdownValue1);
      }, [location, dropdownValue1])

    return (
        <FormControl sx={{ m: 1, minWidth: 220 }}>
            <InputLabel id={inputLabelId}>{dropdownLabel}</InputLabel>
            <Select id={dropdownId} value={dropdownValue} label={dropdownLabel} onChange={handleChange}>
                <MenuItem value={-1}><Chip size="medium" icon={<ArrowCircleDownIcon />} label="Decreasing" color="error" /></MenuItem>
                <MenuItem value={0}><Chip size="medium" icon={<CheckCircleOutlineIcon />} label="No Trend" color="primary" /></MenuItem>
                <MenuItem value={1}><Chip size="medium" icon={<ArrowCircleUpIcon />} label="Increasing" color="success" /></MenuItem>
            </Select>
        </FormControl>
    );
}

And I am invoking the above component from another component multiple times by providing different values for labelId, dropdownID, etc.,

MainComponent.js


import CustomDropdown from '../components/customDropdown.js';

<CustomDropdown inputLabelId="Lbl_Id1" dropdownId="Id1" dropdownValue1={firstSelect} dropdownLabel="First" />
<CustomDropdown inputLabelId="Lbl_Id2" dropdownId="Id2" dropdownValue1={secondSelect} dropdownLabel="Second" />

When trying to retrieve the values of firstSelect & secondSelect after altering the dropdown values, there seems to be no impact.

If anyone could guide me on how to obtain the values for each dropdown in MainComponent.js, it would be greatly appreciated.

Thank you,

Answer №1

Within the realm of React, there exists a fundamental concept known as "lifting up the state".

This essentially involves maintaining the state at the parent level and passing it down to child components along with any necessary callbacks.

In your current situation: You are successfully sending the state to the child component but failing to include the callback functions (setFirstselect or setSecondSelect) needed for updating the state.

Looking specifically at the triggerdropdown.js file, you have an internal state (dropdownvalue) that is being updated locally, thus not affecting the parent state. To address this, I recommend creating separate useState hooks for each TriggerDropDown component in the parent level (maincomponent.js) and passing both the value and corresponding callback to the child component for state updates.

Here's a code snippet to illustrate this:

import TriggerDropDown from '../components/triggerDropDown.js';
const [firstSelect,setFirstselect]=useState();
const [secondSelect,setSecondselect]=useState()
<TriggerDropDown inputLabelId="Lbl_Id1" dropdownId="Id1" dropdownValue1={firstSelect} setState={setFirstselect} dropdownLabel="First" />
<TriggerDropDown inputLabelId="Lbl_Id2" dropdownId="Id2" dropdownValue1={secondSelect} setState={setSecondselect} dropdownLabel="Second" />

And in the TriggerDropdown.js file:

export default function TriggerDropDown({ inputLabelId, dropdownId, dropdownValue1, dropdownLabel, setState }) {
    const [dropdownValue, setDropDownValue] = React.useState('');
    const location = useLocation();

    const handleChange = (event) => { 
        setDropDownValue(event.target.value); 
        setState(event.target.value) 
    };

    React.useEffect(() => {
        setDropDownValue(dropdownValue1);
      }, [location, dropdownValue1])

    return (
        <FormControl sx={{ m: 1, minWidth: 220 }}>
            <InputLabel id={inputLabelId}>{dropdownLabel}</InputLabel>
            <Select id={dropdownId} value={dropdownValue} label={dropdownLabel} onChange={handleChange}>
                <MenuItem value={-1}><Chip size="medium" icon={<ArrowCircleDownIcon />} label="Decreasing" color="error" /></MenuItem>
                <MenuItem value={0}><Chip size="medium" icon={<CheckCircleOutlineIcon />} label="No Trend" color="primary" /></MenuItem>
                <MenuItem value={1}><Chip size="medium" icon={<ArrowCircleUpIcon />} label="Increasing" color="success" /></MenuItem>
            </Select>
        </FormControl>
    );
}

I hope this explanation proves helpful.

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

having trouble installing ReactJS on MacOS

I am facing an issue with setting up ReactJS on my Mac. I am using npm version 4.1.2 and node version v7.7.4. After cloning the project from Git, I navigate to the project folder and try to run 'npm install' followed by 'npm start'. How ...

Encountering null injector errors when running ng test on an Angular application

I have successfully developed a webpage in my Angular application and it is running perfectly. But, when I run ng test, some errors are popping up in Karma like the one shown in the image below: superuser.component.ts // Code for superuser component das ...

Guide to enclosing selected text within a span tag and positioning a div in relation to it using JavaScript

My main objective is to enable the user to: highlight text within a paragraph enclose the highlighted text in a span element add an action button or div at the end of the selected text for further interaction Here's the code I've worked on so ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

Transforming instance of a Class into Json format for WebService

My goal is to retrieve an object of the Product class as a Json for a webservice. Despite successfully loading all the values into the object, I encounter an error when trying to return it as Json. Below is my method: <AllowAnonymous> <HttpGet&g ...

The expansion animation for the Nextjs/React accordion box did not work as expected when utilizing tailwindcss

I am currently working on creating an animation for a collapsible box (accordion). My goal is to have the child component initially hidden with display:none. When I hover over the parent component, the child should be revealed and the dimensions of the pa ...

Steps for including a subdocument within a mongoose schema

I am currently working on setting up a subdocument within a mongoose schema using node.js/Express. There are two schemas in play: Member and Address Member.js // app/models/member.js // Loading mongoose to define the model var mongoose = require(' ...

Issue with Material-UI tab not showing the component upon page load

After setting up material-ui tabs with react-router, I encountered an issue where only the tab names Tab A and Tab B are displayed upon page render. The desired behavior is for the TabAReport component to be automatically rendered without requiring user in ...

Encountering Err_Connection_Refused while working with MVC WebAPI 2 and AngularJS

Seeking guidance on WebAPI, AngularJS, and .NET Authentication, I am currently following a tutorial mentioned HERE. The tutorial is brief (~under 10 mins), but I encountered an error stating Failed to load resource: net::ERR_CONNECTION_REFUSED. Typically, ...

All components in my app are being styled by CSS files

Currently, I am facing an issue with my React app in VS Code. My goal is to assign a distinct background color to each component. However, the problem arises when unwanted CSS styles from other files start affecting components even though they are not impo ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

The bundle.js file is displaying HTML code instead of JavaScript

I have been working on setting up redux server-side rendering using express.js. Most of the setup is done, but I encountered an error while trying to render the page in the browser. The error message Uncaught SyntaxError: Unexpected token < is appearin ...

Organizing angular shapes in alphabetical order

My drop down arrow has elements that are not properly sorted. I have been attempting to use the orderBy angular filter but have encountered some challenges. Upon further investigation, it seems the issue arises because the content I need displayed is neste ...

Creating a personalized scrollball feature within a fancybox

Within my fancybox, I have a section with images that require a scroll bar. I currently have a scroll bar in place, but I am interested in implementing an anti-scroll (custom scrollbar) instead. I came across one option at https://github.com/Automattic/an ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

Error is being thrown due to defining a variable after it has already been declared and

Before I use a variable, I encountered the issue of using it before its definition, interface IProps extends WithStyles<typeof STYLES>; const STYLES = () => ({ }) Although it didn't cause any errors, a warning appeared: STYLES used befo ...

Is there a way to specifically transmit ComponentArt CallbackEventArgs from a JavaScript function during a callback?

One of the challenges I'm facing involves implementing a callback in my ComponentArt CallBack control using javascript when the dropdown list is changed. I specifically want to pass both the control and the associated ComponentArt.Web.UI.CallBackEvent ...

Exploring the depths of React by gaining access to nested objects and arrays

const [data, setData] = useState({ questionText: "", answerOptions: [ { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: & ...

What methods can be used to selectively intercept routes?

On the /job page, when a user clicks on a job in the Link component, it intercepts the route to /job/<jobId>. Is there a way to conditionally redirect the user to the actual page (rendering the entire page without intercepting the route) without hav ...

Maintaining the active state in Bootstrap, even when manually entering a URL, is essential for smooth

Check out this fully functional plnkr example: http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview This example includes a navigation with 2 links (routing to 2 ui-router states), and a jQuery method that ensures the active class remains on the active lin ...