skip to Main Content

I have an app component where I have two child,

  1. a Select component and
  2. a button component
import React from "react";
import { Button } from "@mui/material";
import SelectVariant from "./Components/SelectVariant";
import {category} from "./data";
import { nanoid } from "nanoid";

function App() {
  return(
    <div>
      <SelectVariant 
      values = {category}
      name = "Category"
      />

      <Button variant="contained">Get</Button>
    </div>
  )     
  
}

export default App;`

My ‘Select’ component is a material ui component and it holds its value in its state

import * as React from 'react';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';

export default function SelectSmall(props) {
  const [category, setCategory] = React.useState('');

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

  const menuItems = props.values.map(ele => <MenuItem value={ele}>{ele}</MenuItem>)

  return (
    <FormControl sx={{ m: 1, minWidth: 120 }} size="small">
      <InputLabel id="demo-select-small">{props.name}</InputLabel>
      <Select
        labelId="demo-select-small"
        id="demo-select-small"
        value={category}
        label={props.name}
        onChange={handleChange}
      >
        {menuItems}
      </Select>
    </FormControl>
  );
}

I want to console log the value my Select component is holding when I click on the Button Get

How should I go about this? or should I set up the state in the app component somehow?

2

Answers


  1. If you don’t want to use the same state and keep it in the parent component, so you have to create a state inside it anyway and pass its setter to the child component and from the child component each time you update the wanted state you update the state created in the parent component so they will be synchrones.
    Now from the parent component you just have to log the created state.

    I would go for the first approach.

    Login or Signup to reply.
  2. You’ve got two options: 1) either raise the state from the child component to the parent component, or 2) use the context API.

    I’m partial to the context API because it avoids prop drilling.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search