“This is my 28th day of participating in the First Challenge 2022. For details: First Challenge 2022.”

In this article, we’ll write a simple search plug-in in React. With this article, I hope to help developers understand how to write plugins using React, publish them to NPM, and deploy the demo to Github.

start

We’ll use create-React-Library, which is a CLI for creating reusable reaction libraries. The CLI has a number of features that will help us generate templates for our plug-ins.

To use create-react-library, we need to install it globally:

npm install -g create-react-library
Copy the code

The command above will install create-react-library globally, and we can generate a new module from any directory. To generate a new directory, type the following command in the directory where you want to boot the plug-in:

create-react-library
Copy the code

The command above will ask for some basic hints about your module, and once you answer them, a sample of the plug-in will be generated.

Now you need to run the plug-in (to see any changes you made to it) and the sample. In a TAB, you can run:

cd react-search-box && yarn start
Copy the code

Also, in another TAB, you need to run the sample application:

cd react-search-box/example && yarn start
Copy the code

The last command will run a create-react-app project that imports the plug-in. If you make any changes to the plug-in, it will be reflected in the sample application. You can view the current status of the plug-in by visiting http://localhost:3000.

The initial state of the plug-in after booting with create-react-library

Design input box

Let’s add the first basic feature: an input box that allows the user to enter.

import React, { Component } from 'react'import PropTypes from 'prop-types'
Copy the code
import styles from './styles.css'
Copy the code
export default class ReactSearchBox extends Component {  static propTypes = {    /**     * value: The default value for the input box.     * placeholder: The placeholder text for the input box.     */    value: PropTypes.string,    placeholder: PropTypes.string  }
Copy the code
  state = {    value: ''  }
Copy the code
  componentDidMount() {    const { value } = this.props
Copy the code
    this.setState({      value: value    })  }
Copy the code
  handleInputChange = e => {    const { value } = e.target
Copy the code
  this.setState({      value: value    })  }
Copy the code
  inputNode = () => {    /**     * This function is responsible for rendering the input box.     * The input box acts as a source of entry for the data from the user.     */    const { placeholder } = this.props    const { value } = this.state
Copy the code
    return (      <input        className={styles.input}        type='text'        placeholder={placeholder}        value={value}        onChange={this.handleInputChange}      />    )  }
Copy the code
  render() {    return <div className={styles.container}>{this.inputNode()}</div>  }}
Copy the code

In the code above, we create an input element with a className attribute, a Type attribute, a placeholder attribute, a value attribute, and an onChange handler. Most of them are very basic items. The only interesting item is the one that onChange triggers every time the user types in the input box.

We call this handleInputChange function every time the input box changes. The handleInputChange function takes the event as its argument. We use the ES6 arrow function here. So, we don’t need to explicitly bind this function, handleInputChange. You can read James K Nelson’s when to use arrow functions in React.

Since we have a state in which value is passed as a property to the input box, value therefore updates the state whenever the input box changes through the handleInputChange function.

handleInputChange = e => {  const { value } = e.target
Copy the code
  this.setState({    value  })}
Copy the code

If you visit http://localhost:3000, you will see an input box on the screen. You can enter in the input box and the values will be updated.

Initial state of input box

If you check in React Developer Tools, you’ll see that the value of the input box is being updated.

That’s all we need for our input box. Next, we’ll design a drop-down list that will appear as soon as the string the user types into the input box matches any records that will be provided to us through prop for the plug-in.

Design drop-down menus

In this section, we implement a drop-down list that displays an array of records that match the string the user typed into the input box. The initial record array will be provided using data, the item we will implement first.

import React, { Component } from "react"; import ReactSearchBox from "react-search-box";Copy the code
export default class App extends Component {  data = [    {      key: "john",      value: "John Doe"    },    {      key: "jane",      value: "Jane Doe"    },    {      key: "mary",      value: "Mary Phillips"    },    {      key: "robert",      value: "Robert"    },    {      key: "karius",      value: "Karius"    }  ];
Copy the code
  render() {    return (      <div className="container">        <ReactSearchBox          placeholder="Placeholder"          value="Doe"          data={this.data}        />      </div>    );  }}
Copy the code

Our plug-in should be imported and defined like the code block above. You import the ReactSearchBox, and then pass the object Data array (arrays in this case) to the ReactSearchBox.

Value Now, if we pass prop to our plug-in, we will render the drop-down list. Later, if any record data in prop matches the supplied prop, we refactor our component to display the drop-down list value.

Our plugin now looks like this:

import React, { Component } from 'react'import PropTypes from 'prop-types'
Copy the code
import styles from './styles.css'
Copy the code
export default class ReactSearchBox extends Component {  static propTypes = {    /**     * value: The default value for the input box.     * placeholder: The placeholder text for the input box.     * data: An array of objects which acts as the source of data for the dropdown.     */    value: PropTypes.string,    placeholder: PropTypes.string,    data: PropTypes.array.isRequired  }
Copy the code
  static defaultProps = {    /**     * Set data prop as an empty array in case it's not passed.     */    data: []  }
Copy the code
  state = {    value: ''  }
Copy the code
  componentDidMount() {    /**     * This function is the same as before     */    }
Copy the code
  handleInputChange = e => {    /**     * This function is the same as before     */    }
Copy the code
  inputNode = () => {    /**     * This function is the same as before     */  }
Copy the code
  dropdownNode = () => {    /**     * This function is responsible for rendering the dropdown.     */    const { data } = this.props
Copy the code
    return (      <div className={`react-search-box-dropdown ${styles.dropdown}`}>        <ul className={styles.dropdownList}>          {data.map(record => {            return (              <li                key={record.key}                className={`react-search-box-dropdown-list-item ${                  styles.dropdownListItem                }`}              >                {record.value}              </li>            )          })}        </ul>      </div>    )  }
Copy the code
render() {    return (      <div className={styles.container}>        {this.inputNode()}        {this.dropdownNode()}      </div>    )  }}
Copy the code

The code for the dropdown menu exists in the dropdownNode function. Based on the items data gave us for the plugin, we are creating a list of Li items to present in a drop-down list.

If we visit http://localhost:3000/, we will see a drop-down menu and an input box.


That’s all you need for a drop-down menu. Next, we’ll refactor our plug-in to render the drop-down menu only if any records match the query the user will type into the input box.