react-input-with-select

2.0.0 • Public • Published

Input with Select in React

Introduction

This is a react specific library for use react-input-with-select.

Install

Install dependencies

npm i react-input-with-select

How to Use

In your component import

 import { ReactInputWithSelect } from 'react-input-with-select';

Add the Component (please follow strictly)

 import React, { useState, useEffect } from "react";
 import { ReactInputWithSelect } from 'react-input-with-select';

 const App = () => {
  const [name, setName] = useState("");
  const [options, setOptions] = useState([]);
  const [selectedData, setSelectedData] = useState(null);

  const handleChange = (e) => {
    # you will get name in e.targert.value
    if (e.target.value.length > 0) {
      setName(e.target.value);
      setSelectedData(null);
    }
  };

  const handleClick = (option) => {
    # you will get the selected option here with id, label and value
    console.log(option);
    setName(option.value);
    setSelectedData(option);
  };

  useEffect(() => {
    let arr = [];
    const getOptions = () => {
        # I am using fetch and free api just for example you can use anything
        # But you need to set the give format.
      fetch("https://jsonplaceholder.typicode.com/comments")
        .then((res) => res.json())
        .then((result) => {
          arr = result?.map((re) => {
            return {
              id: re.id,
              label: re.name,
              value: re.name,
            };
          });
          setOptions(arr);
        });
    };
    # This condition need to be used as it is
    if (name.length > 0 && !selectedData) {
      getOptions();
    } else {
      setOptions([]);
    }
  }, [name]);

  console.log(name);
  console.log(selectedData);
  console.log(options);

  return (
    <div>
      <ReactInputWithSelect
        name={name}
        setName={setName}
        options={options}
        setOptions={setOptions}
        selectedData={selectedData}
        setSelectedData={setSelectedData}
        handleChange={handleChange}
        handleClick={handleClick}
      />
    </div>
  );
};

export default App;

Package Sidebar

Install

npm i react-input-with-select

Weekly Downloads

3

Version

2.0.0

License

none

Unpacked Size

9.11 kB

Total Files

5

Last publish

Collaborators

  • sohit_kumar