How to clear a material-ui search input using a button

Viewed 4612

Working on a tutorial atm that involves react material-ui tables that also has a search input textfield. What I am trying to add to it, is a button that will reset the table report but also clear the search input textfield.

It is the clearing of the search textfield that I am having trouble with.

They are using this code as a separate component library called Controls.input:

import React from 'react' import { TextField } from '@material-ui/core';

export default function Input(props) {

    const { name, label, value,error=null, onChange, ...other } = props;
    return (
        <TextField
            variant="outlined"
            label={label}
            name={name}
            value={value}
            onChange={onChange}
            {...other}
            {...(error && {error:true,helperText:error})}
        />
    )
}

The main search code is as follows where I have also added a button

            <Controls.Input
                id="name"
                label="Search Name"
                className={classes.searchInput}
                InputProps={{
                    startAdornment: (<InputAdornment position="start">
                        <Search />
                    </InputAdornment>)
                }}
                onChange={handleSearch}
            />
            <Button
                onClick={handleClear}
                className="materialBtn"
            >
                Clear
            </Button>

At this point, I am not sure how to reference/target the search input field as part of the handleClear function, in-order to clear it's contents?

const handleClear = () => {
    ????
}    

Do I need to use useState()?

1 Answers

You are right with having to put the value into state. Based on what you have supplied it seems that your state needs to be in your parent component. So something like this should work

import { useState } from 'react'

const ParentComponent = () => {
    const [value, setValue] = useState('')

    const handleClear = () => {
        setValue('')
    }

    const handleSearch = (event) => {
        setValue(event.target.value)
    }

    return (
        <>
            <Controls.Input
                id="name"
                label="Search Name"
                className={classes.searchInput}
                value={value}
                onChange={handleSearch}
                InputProps={{
                    startAdornment: (
                        <InputAdornment position="start">
                            <Search />
                        </InputAdornment>
                    ),
                }}
                
            />
            <Button onClick={handleClear} className="materialBtn">
                Clear
            </Button>
        </>
    )
}

Related