React HTML Datalist
React HTML Datalist is a simple component that makes it easier to work with html <datalist>
tag in React. The usage of this component is very similar to that of the <select>
tag.
What problem does it solve?
Unlike the <select>
tag in html, a <datalist>
tag does not provide the flexibility to manage different value and text for an <option>
.
For example, option for select
can be given as:
<option value="1">Pizza</option>
but option for datalist
is given as:
<option value="Pizza" />
Hence, React HTML Datalist makes it easier to manage both text and value for options in datalist.
Installation
It's easy to install react-html-datalist
, no extra piece of code is needed.
Simply run the command:
npm install react-html-datalist
Usage
To use the react-html-datalist
component you can simply import it and pass the related props. Moreover, the component can be used with both class and function components. Refer to the examples below.
Examples
# Function Component
import React useState from "react";import ReactDOM from "react-dom";import ReactHTMLDatalist from "react-html-datalist"; const App = { const detail setDetail = ; const handleChange = { ; }; return <div ="App"> <h1>React HTML Datalist</h1> <p> <b>Selected food id:</b> detailfood_id || "(none)" </p> <small>Search or select in the datalist: </small> <ReactHTMLDatalist = = = = /> </div> ;}; ;
react-html-datalist
with function components (hooks) on codesandbox:
Try
# Class Component
import React from "react";import ReactDOM from "react-dom";import ReactHTMLDatalist from "react-html-datalist"; Component { ; thisstate = food_id: "" ; } { this; }; { var food_id = thisstate; return <div ="App"> <h1>React HTML Datalist</h1> <p> <b>Selected food id:</b> food_id || "(none)" </p> <small>Search or select in the datalist: </small> <ReactHTMLDatalist = = = = /> </div> ; } ;
react-html-datalist
with class components on codesandbox:
Try
Props
The component can be provided with the following props:
prop | datatype | example | is required |
---|---|---|---|
name | string | "myform" | yes |
classNames | string | "class-one class2" | no |
styles | object | { color: "#0cc" } | no |
onChange | function | handleChange | yes |
options | array | [ { text:"pizza" ,value:1 }, { text: "burger", value: 2 } ] | yes |
Note: The component does not require a
value
prop. It manages value on it's own via the providedonChange
prop.
License
MIT
Enjoy!