Importing a React component from a separate file

Currently utilizing the React Material-UI library, I am faced with a challenge in implementing a search 'filter' on the main/parent page that should trigger a Drawer component located in a separate file.

While I grasp the concept of how this functions within one file, I'm struggling to divide it into distinct files for better code organization. Moreover, extracting the 'variables' from the Drawer for selected items has proven to be a hurdle. Below, you'll find snippets from my parent and child files where I aim to have an 'onclick' event in the parent file launch the Drawer in the child file. Any assistance would be greatly appreciated!

Here is a section of my parent file:

return (
    <Autocomplete
      id="search"
      ...
      renderInput={(params) => (
        <TextField
          {...params}
          label="Search for an item"
          variant="outlined"
          InputProps={{
            ...params.InputProps,
            startAdornment: (
              <InputAdornment position="start">
                <IconButton color="primary" aria-label="filters" component="span">
                  <TuneRoundedIcon onClick={ handleFilterOpen } />
                </IconButton>
                <Filter open={ openFilter} />
              </InputAdornment>
            ),
            endAdornment: (
              <React.Fragment>
                {loading ? <CircularProgress color="inherit" size={20} /> : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
          fullWidth
        />
      )}

And here's a snippet from the Filter.tsx (child file):

export default function Filter() {
const classes = useStyles();
const theme = useTheme();
const [open, setOpen] = React.useState(false);

const handleDrawerOpen = () => {
   setOpen(true);
};

const handleDrawerClose = () => {
    setOpen(false);
};

return (
<Drawer
    className={classes.drawer}
    variant="persistent"
    anchor="right"
    open={open}
    classes={{
      paper: classes.drawerPaper,
    }}
  >
    <div className={classes.drawerHeader}>
      <IconButton onClick={handleDrawerClose}>
        {theme.direction === 'rtl' ? <ChevronLeftIcon /> : <ChevronRightIcon />}
      </IconButton>
    </div>
    <Divider />
    <List>
      {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
        <ListItem button key={text}>
          <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
          <ListItemText primary={text} />
        </ListItem>
      ))}
    </List>
    <Divider />
    <List>
      {['All mail', 'Trash', 'Spam'].map((text, index) => (
        <ListItem button key={text}>
          <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
          <ListItemText primary={text} />
        </ListItem>
      ))}
    </List>
  </Drawer>
);
}

Answer №1

To ensure proper communication, you should pass the open state from the parent component to the child component through props. The child component itself should not have its own "open" state. Here's a simplified version for better clarity:

const Parent = () => {
  const [open, setOpen] = React.useState(false);
  const toggleOpen = () => {
     setOpen(!open)
  }
  
  const customFunction(valueFromChildComponent) {
    alert(valueFromChildComponent); // This will alert "myValue" as it is passed from the child component
  }
  
  return (
    <Child isOpen={open} myCustomFunction={customFunction} />
  );  
}

Child component

const Child = props => {      
  return (
    console.log(props.isOpen) // The value passed down from the parent is accessed via props.isOpen
    <button onClick={props.myCustomFunction("myValue")}>Test Button</button>
  );  
}

I've also provided an example of how you can pass a value from your child component back to the parent. In this case, I passed up a string, but you could pass up any type of data such as the selected value of a dropdown or any other information you need.

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

Managing the state in NextJS applications

I've scoured the depths of the internet in search of a solution for this issue, but unfortunately I have yet to come across one that effectively resolves it. I've experimented with various state management tools including: useContext Redux Zusta ...

What is the advantage of not importing related modules?

As a newcomer to React, please excuse any novice questions I may have. I am currently utilizing npx create-react-app to develop a React app, but I'm unsure of the inner workings: Q1-If I were to throw an error in a component like so: import React, { ...

Implementing a Button Click Event Listener on a Separate Component in React

Currently, my React application incorporates MapBox in which the navbar is its parent component. Within the navbar component, there is a button that collapses the navbar when clicked by changing its CSS class. I also want to trigger the following code snip ...

Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well. If I change the type attribute to ...

Utilizing getStaticProps for Performance Optimization in Next.js

I am currently in the process of setting up a blog using Next.js and GraphCMS. I have an ArticleList component that I want to display on multiple pages, such as my homepage and under each article as a recommendation. Since the article list is sourced from ...

Transitioning from mui version 4 to version 5 leads to an error message: "TypeError: Cannot access 'keyboardDate' properties of undefined"

After updating from MUI v4 to version v5, I encountered failing tests with the following error: TypeError: Cannot read properties of undefined (reading 'keyboardDate') 17 | it("should render correctly without any errors", () =& ...

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

Issue encountered: ENOENT - There is no file or directory located at the specified path for ... .steampath

I am encountering an issue while attempting to launch the development server on a React project that has been dormant for quite some time. After executing npm install and npm start, I encountered the following error message. Despite my efforts to manua ...

Retrieve the initial value from the TextField

My website features multiple filters, including by date and duration, allowing users to easily find the information they need from a large dataset. There is also a "reset all filters" button that clears all filters and displays the full list of products. ...

Interactive Image Component in React

I'm encountering an issue with my React code. import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import RecipeService from "./RecipeService"; import RecipeProfileImg from "./Re ...

Prevent input from being cleared when selecting an option with React-Select

Unfortunately, there was no satisfactory solution to this question so I will provide an answer: The issue arises when trying to utilize React-Select with a persistent input value that remains even after selection or blurring. Regrettably, this functionali ...

Using the DatePicker component with non-escaped Latin alphabet characters in date-fns for ReactJS

While attempting to integrate the DatePicker component from Material UI into my React project, I encountered an error. Although many attributed the issue to a version discrepancy, what ultimately resolved the problem for me was assigning a value to the Da ...

How do I incorporate scrolling into Material-UI Tabs?

I am currently incorporating Material-ui Tablist into my AppBar component. However, I am facing an issue with the responsiveness of the tabs. When there are too many tabs, some of them become hidden on smaller screens. For more information on the componen ...

What is the best way to implement the Snackbar functionality within a class-based component?

My snackbar codes are not working as expected when I click the "confirm" button. I want the snackbar to appear after clicking the button. Most examples I've seen use functional components, so how can I get the Snackbar to work properly in a class comp ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

Adjust the height setting of the React-Highcharts viewport

My initial configuration for highcharts looks like this:- function getInitialHighChartsConfig(chartType) { return { credits: false, chart: { type: chartType, height: 325, }, title: { text: '', useHTML: tr ...

Creating a dynamic state management system for multiple Collapse components can be achieved by utilizing

I am trying to create a Collapse menu from array data, Currently, when I click on any menu all sub menus expand I believe my issue lies in not being able to set a unique "open" state for each Main menu I want to avoid assigning a "state" to accommodate ...

Developing a transparent "cutout" within a colored container using CSS in React Native (Layout design for a QR code scanner)

I'm currently utilizing react-native-camera for QR scanning, which is functioning properly. However, I want to implement a white screen with opacity above the camera, with a blank square in the middle to indicate where the user should scan the QR code ...

Utilize React.js ThemeProvider to dynamically change themes based on routing

Hey everyone, I have a question regarding changing the theme provider based on the route in my code snippet: const rootElement = document.getElementById('root'); ReactDOM.render( <ThemeProvider theme="MyThemes.default& ...