Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140220

React passing state value to parent

$
0
0

I am learning react and encounter this problem with the state values. I have a function component(child) that has drop down boxes to select and they all have their own state. When the confirm button is clicked, the state values are passed to the parent class using a prop function.

(Child class)
export default function NativeSelects(props){
    const [search_title, setTitle] = useState('')
    const [search_category,setCategory] = useState('')

    return (
        <div>
            <FormControl className={classes.formControl}>
                <InputLabel htmlFor="age-native-simple">Title</InputLabel>
                <Select
                    native
                    value={search_title}
                    onChange={e => setTitle(e.target.value)}
                    inputProps={{
                        name: 'search_title',
                        id: 'age-native-simple'
                    }}
                >
                    <option value="" />
                    <option value="option1">option1</option>
                    <option value="option2">option2</option>
                    <option value="option3">option3</option>
                </Select>
            </FormControl> 
            <FormControl className={classes.formControl}>
                <InputLabel htmlFor="age-native-helper">Category</InputLabel>
                <Select
                    native 
                    value={search_category}
                    onChange={e => setCategory(e.target.value)}
                    inputProps={{
                        name: 'search_category',
                        id: 'age-native-simple'
                    }}
                >
                    <option value=""/>
                    <option value="option1">option1</option>
                    <option value="option2">option2</option>
                    <option value="option3">option3</option>
                </Select>
            </FormControl>
            <Button variant="contained" color="primary" onClick={props.handler(search_title,search_category)}>Search</Button>
        </div>
    )
}
(Parent class)
searchProduct = (title,category) =>{
    fetch(`/search?title='${title}'&category='${category}'`)
    .then(response => response.json())
    .then(response => this.setState({ products: response.data }))
    .catch(err => console.error(err))
  }

  render(){
    return (
        <ChildClass handler = {() => this.searchProduct}/>
    )
  }

When I check the state values inside the child class, it is changing properly. But in the parent class the first value becomes an object and the second value becomes undefined. What did I do wrong here?


Viewing all articles
Browse latest Browse all 140220


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>