Create a tags input component in React
Today you will learn how to create a tags input component in React. In other words, we will show you how to create a comma separated tags in the input field.
Checkout more articles on ReactJS
Demo Application
Steps to create a tags input component in React
1. Install package
Here, we will use the react-tagsinput NPM package to create a tags input in React component. Run the following command to install the package.
1 | npm i react-tagsinput |
2. Add tags input in component
Just like other react packages, we have to import it on top and render the tags in the react component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import React, { useState } from 'react'; import TagsInput from 'react-tagsinput'; import 'react-tagsinput/react-tagsinput.css'; function App() { const [tags, setTags] = useState([]); const handleChange = value => { setTags(value); } return ( <div className="app"> <h4>Create a tags input component in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4> <TagsInput inputProps={{ placeholder: 'Enter tags' }} className='tag-box react-tagsinput' maxTags={10} value={tags} onChange={handleChange} /> <div>Tags: {tags.join(', ')}</div> </div> ); } export default App; |
This is a simple and easy to use for tags input. Here you can also pass additional props such as maxTags
, inputProps
and many more. Click Here to check more props.
3. Output
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂