How to get the TextField value with onclick button event React Material UI

Viewed 2737

I am trying to get the input value of a search TextField, then on the click of "Search" button, call the API with the search input. Here's what I have so far:

const handleSearchSubmit = async () => {
        
        setSearchTerm(searchForm.current.value)
        console.log(searchTerm)

        const fetchSearch = async () => {
            const params = {searchTerm: searchTerm}
            console.log(params)
            const response = await axios("/api/search", { params });
            const data = response.data
            setResTable(data)
            console.log(resTable)
        };
        fetchSearch();
    };



<TextField
                                id="searchInput"
                                inputRef={searchForm}
                                style={{ margin: 8 }}
                                placeholder="Enter a code or procedure"
                                fullWidth
                              />
                              </FormGroup>
                        </Col>
                        <Button variant="contained" color="primary" onClick={handleSearchSubmit}>
                            Search
                        </Button>

I cannot seem to get the value of the TextField input. When I console.log it, I get an empty array. Any suggestions?

1 Answers

You need to use onChange in your TextField.

Create a state variable and set it in onChange.

<TextField
          id="searchInput"
          inputRef={searchForm}
          onChange={(v) => setValue(v.target.value) } //Add your setVariable to this line
          style={{ margin: 8 }}
          placeholder="Enter a code or procedure"
          fullWidth
          >

Then use the variable to do your search.

Related