Skip to main content

Search

Base​

Search on submit​

The onSubmit property must be used to define a callback that will be called when the user clicks the submit button or presses enter on the keyboard.

Search on change​

The onChange property is used to define a callback that will be called when the user types something.

The onClear property​

The onClear property is used to define a callback that will be called when the user clicks the clear button.

Setting up a default value​

To render Search with an initial value it is necessary to use the defaultValue property. With it, the Search component will handle state changes by itself.

Controlling the state change's​

To control state changes, it is necessary to use the value property together with the callback onChange return.

The loading property​

It is possible to add the loading property to display a Spinner, indicating that some asynchronous search is running.

tip

Use a debounce function inside the callback onChange when you need to do an asynchronous action, like an HTTP request for example . Learn more about debounce and throttle here.

React Hook Form​

Use the Search component together with the React Hook Form. To do this, install this dependency in the project.

yarn add react-hook-form
import React from 'react';
import { useForm } from 'react-hook-form';
import {
Form,
Search,
Button,
Text
} from '@resultadosdigitais/tangram-components';

export default function WithReactHookForm() {
const {
register,
handleSubmit,
formState: { errors }
} = useForm();
const [submitted, onSubmit] = React.useState();

return (
<>
{submitted && (
<Text>
<strong>Submitted:</strong> <code>{JSON.stringify(submitted)}</code>
</Text>
)}

<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Control error={Boolean(errors.search)}>
<Form.Label htmlFor="search-with-rhf">Search</Form.Label>
<Search
id="search-with-rhf"
name="search"
placeholder="Type your search..."
aria-describedby="search-with-rhf"
onSubmit={handleSubmit(onSubmit)}
{...register('search', { required: true })}
/>

{errors.search && (
<Form.Feedback id="search-with-rhf-feedback">
This field is required
</Form.Feedback>
)}
</Form.Control>
<Button type="submit">Submit</Button>
</Form>
</>
);
}

See and test the full example below:

Feedback​

2