Search code examples
reactjsreact-hooksrxjs

How to sent value on Select to another page


I want to get value from select.js to index.js i have no idea to get it on index.js

Select.js

const SelectSmall = () => {
const [ProJect, setProJect] = React.useState("");


return (
  <FormControl sx={{ m: 1, minWidth: 150 }} size="small">
    <h1>{ProJect}</h1>
    <InputLabel id="Projects">Project</InputLabel>
    <Select
      labelId="Projects"
      id="Projects"
      value={ProJect}
      label="Project" 
      onChange={e=>setProJect(e.target.value)}
      
    >
      <MenuItem value="">
        <em>None</em>
      </MenuItem>
      <MenuItem value={'ma'}>MA-Network</MenuItem>
      <MenuItem value={'ns'}>Network-Security</MenuItem>
      <MenuItem value={'fz'}>Freezone</MenuItem>
      <MenuItem value={'ma-2'}>MA-Network2</MenuItem>
    </Select>
  </FormControl>
);
}

  export default SelectSmall;

Index.js

import React from 'react'
import SelectSmall from "./select"
export const App> = () => {
return (
   <div>
     <h1><SelectSmall.Project><h1>

   </div>
  )
}

Solution

  • In your Select component you need to add one more function via its properties to send the value to the parent component

    const SelectSmall = props => {
    

    . . .

    <Select
          labelId="Projects"
          id="Projects"
          value={ProJect}
          label="Project" 
          onChange={e=> handleValueChange(e)}
        >
    

    . . .

    const handleValueChange = e => {
      setProJect(e.target.value)
      props.getValue(e.target.value)
    } 
    

    And the add a new function in parent component to use this new value

    import React from 'react'
    import SelectSmall from "./select"
    export const App> = () => {
     
    const printSelectValue = val => {
      console.log(val)
    }
    
    return (
       <div>
         <h1><SelectSmall getValue={printSelectValue}><h1>
    
       </div>
      )
    }