javascriptreactjsreact-select-search

Getting the onchange text in react-select search component


I am trying to get search select functionality in my page using the react select search npm package.

my parent component

import React, { Component } from "react";
import Task from "./task";
class TaskList extends Component {
  state = {
    taskList: [
      {
        id: 1,
        taskname: "",
        taskdate: new Date(),
        taskstatus: "",
        taskdesc: ""
      }
    ],
    statusOptions: [
      { id: 1, name: "Pending", value: "Pending", key: "Pending" },
      { id: 2, name: "In-Progress", value: "In-Progress", key: "In Progress" },
      { id: 3, name: "Completed", value: "Completed", key: "Completed" }
    ]
  };
  addNewtask = () => {
    let lastTaskId;
    if (this.state.taskList.length !== 0) {
      lastTaskId = this.state.taskList[this.state.taskList.length - 1].id;
      lastTaskId = lastTaskId + 1;
    } else {
      lastTaskId = 1;
    }
    this.setState((prevState) => ({
      taskList: [
        ...prevState.taskList,
        {
          id: lastTaskId,
          taskname: "",
          taskdate: new Date(),
          taskstatus: "",
          taskdesc: ""
        }
      ]
    }));
  };
  handletaskDelete = (taskId) => {
    const taskList = this.state.taskList.filter((task) => {
      return taskId !== task.id;
    });
    this.setState({ taskList });
  };
  setStartDate = (data, taskId) => {
    this.setState((prevState) => ({
      taskList: prevState.taskList.map((obj) =>
        obj.id === taskId
          ? Object.assign(obj, { taskdate: new Date(data) })
          : obj
      )
    }));
  };
  selectOptionChange = (data, taskId) => {
    this.setState((prevState) => ({
      taskList: prevState.taskList.map((obj) =>
        obj.id === taskId ? Object.assign(obj, { taskstatus: data }) : obj
      )
    }));
  };
  setTaskDesc = (data, taskId) => {
    this.setState((prevState) => ({
      taskList: prevState.taskList.map((obj) =>
        obj.id === taskId ? Object.assign(obj, { taskstatus: data }) : obj
      )
    }));
  };
  setTaskName = (data, taskId) => {
    this.setState((prevState) => ({
      taskList: prevState.taskList.map((obj) =>
        obj.id === taskId ? Object.assign(obj, { taskname: data }) : obj
      )
    }));
  };
  handleValidation() {
    const taskList = this.state.taskList.filter((task) => {
      return task.taskname !== "";
    });
    this.setState({ taskList });
  }
  saveTasks = () => {
    this.handleValidation();
    const localTaskList = this.state.taskList;
    console.log("check", localTaskList);
    //  localStorage.setItem('tasklist', JSON.stringify(localTaskList));
  };
  componentDidMount() {
    //  let taskList;
    //  const localTaskList = localStorage.getItem('tasklist') !== null
    //  if (localTaskList) {
    //      console.log("enter")
    //      taskList = JSON.parse(localStorage.getItem('tasklist'))
    //  } else {
    //      taskList = [{ id: 1, taskname: "", taskdate: new Date(), taskstatus: "", taskdesc: "" }]
    //  }
    //  this.setState({taskList});
    console.log(
      "render",
      typeof this.state.taskList,
      this.state,
      localStorage.getItem("tasklist")
    );
    //  { id: lastTaskId, taskname: "", taskdate: new Date(), taskstatus: "", taskdesc: "" }
  }
  render() {
    let { taskList, statusOptions } = this.state;
    return (
      <div>
        <table>
          <thead>
            <tr>
              <th>Task Name</th>
              <th>Task Date</th>
              <th>Task tatus</th>
              <th>Task Description</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <Task
              taskList={taskList}
              statusOptions={statusOptions}
              setTaskName={this.setTaskName}
              setTaskDesc={this.setTaskDesc}
              selectOptionChange={this.selectOptionChange}
              onTaskDelete={this.handletaskDelete}
              setStartDate={this.setStartDate}
            />
          </tbody>
          <tfoot>
            <tr>
              <td>
                <button onClick={this.addNewtask}>Add list</button>
              </td>
            </tr>
            <tr>
              <td>
                <button onClick={this.saveTasks}>Save</button>
              </td>
            </tr>
          </tfoot>
        </table>
        {/* { this.state.taskList.map(task => {task.id}) } */}
      </div>
    );
  }
}

export default TaskList;

Task component which makes use of selectSearch package

import React from "react";
import DatePicker from "react-datepicker";
import SelectSearch from "react-select-search";
import "react-datepicker/dist/react-datepicker.css";
import "./tasklist.css";
const Task = (props) => {
  return props.taskList.map((task, idx) => {
    let taskName = `taskname-${idx}`,
      taskDate = `taskdate-${idx}`,
      taskDesc = `taskdesc-${idx}`,
      taskStatus = `taskstatus-${idx}`,
      taskDelete = `taskdelete-${idx}`;
    return (
      <tr key={task.id} className={task.taskstatus}>
        <td>
          <input
            type="text"
            name="taskName"
            data-id={idx}
            id={taskName}
            onChange={(data) => props.setTaskName(data, task.id)}
          />
        </td>
        <td>
          <DatePicker
            selected={new Date(task.taskdate)}
            id={taskDate}
            onChange={(data) => props.setStartDate(data, task.id)}
          />
        </td>
        <td>
          <textarea
            name="textarea"
            rows="4"
            cols="50"
            data-id={idx}
            id={taskDesc}
            onChange={(data) => props.setTaskDesc(data, task.id)}
          ></textarea>
        </td>
        <td>
          <SelectSearch
            options={props.statusOptions}
            onChange={(data) => props.selectOptionChange(data, task.id)}
            name="taskStatus"
            data-id={idx}
            id={taskStatus}
            placeholder="Choose task status"
          />
        </td>
        <td>
          <button
            data-id={idx}
            id={taskDelete}
            onClick={() => props.onTaskDelete(task.id)}
          >
            Delete
          </button>
        </td>
      </tr>
    );
  });
};
export default Task;

So far i was able to get the selected text using the onChange function in the package.My aim is to get the onChange text from the input box as we type.i have tried passing the onKeyUp props into the select search component and tried to get the e value into a function and was not successful is there a way to achieve this?.


Solution

  • after going through the documentation i came across a functional prop called getOptions which can provide the search query which we pass to the component and later set it to a state so that i could persist the value in the fields.

    https://www.npmjs.com/package/react-select-search#custom-renderers

    what i did,

    added getOptions={myFunction} in the component and enables search={true}

    const [task,setTask]=useState(null);
     <SelectSearch
                options={props.statusOptions}
                id="input1"
                getOptions={myFunction}
                onChange={(data) => props.selectOptionChange(data, task.id)}
                name="taskStatus"
                search={true}
                data-id={idx}
                value={task}
                placeholder="Choose task status"
              />
    
    const myFunction=(val)=>{
    setTask(val);
    }