Hello all.. i need help in react-data-grid function - reactjs

import logo from './logo.svg';
import './App.css';
import React, { useRef, useState } from 'react';
import "react-data-grid/lib/styles.css";
import DataGrid, { textEditor } from "react-data-grid";
import {Calendar } from "react-calendar";
const DatePicker = () => {
  const [date, setDate] = useState('');
  const dateInputRef = useRef(null);
  const handleChange = (e) => {
    setDate(e.target.value);
  };
const validateEmail = value => {
if (!value) return "Email is required";
if (!/^[a-zA-Z0-9]+#[a-zA-Z0-9]+\.[A-Za-z]+$/.test(value))
return "Invalid email address";
};
//The error has been fixed.
const columns = [
{ key: "id", name: "ID",editor:textEditor },
{ key: "date", name: "Date",editor:textEditor },
{ key: "email", name: "email",editor:textEditor,validate:validateEmail},
];
const rows = [{ id: 0, date: "2023-01-02", email: "jane#example.com" }];
function App() {
return <DataGrid columns={columns} rows={rows} />;
}
);
//export default App;
  return (
    <div>
      <input
        type="date"
        onChange={handleChange}
        ref={dateInputRef}
      />
      <p>Selected Date: {date}</p>
    </div>
  );
};`enter code here`
export default DatePicker;`
Hello world, i creat a script for get date.but When I click on date my calendar not come out plese solve my problem. I add my code here and add image.This code i run in termux and my all packages is installed in device

Related

React Datepicker for rendering list is always one day behind

I am building a ToDoList with React and a Django rest Api but I am also using a Datepicker to render all the tasks for the day by the date created. So if I choose the 12.06 the api calls all the tasks for that day and displays them. But every time I change the date to show the list for the day the list for that day is not shown.
Only if i change it to another day the list of the previous date is shown. For example I choose the 12.06 nothing appears but then switch to the 11.06 the tasks for the 12th are being rendered. If I console log the dates in the Datepicker it shows the right day but if I do it inside the handleDateChange I hangs behind.
import 'date-fns'
import Grid from '#material-ui/core/Grid'
import DateFnsUtils from '#date-io/date-fns'
import{
MuiPickersUtilsProvider,
KeyboardTimePicker,
KeyboardDatePicker
} from '#material-ui/pickers'
import TodoForm from '../ToDo/TodoForm'
function Datepicker() {
const initialDate = new Date(Date.now())
const [selectDate, setSelectDate] = useState(
`${initialDate.getFullYear()}-${initialDate.getMonth()+1}-${initialDate.getDate()}`
)
console.log("In App selected Date = ", selectDate)
const handleDateChange = (date) =>{
// setSelectDate(date)
setSelectDate(`${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`)
console.log("TimePicker selected Date = ", selectDate)
}
return (
<div>
<div>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container justify='space-around'>
<KeyboardDatePicker
disableToolbar
varient='inline'
format='MM/dd/yy'
margin='normal'
id='date-picker'
label='Pick your Date'
value={selectDate}
onChange={handleDateChange}
KeyboradButtonProps={{
'aris-label': 'change date'
}}
/>
</Grid>
</MuiPickersUtilsProvider>
</div>
<div>
<TodoForm date={selectDate}/>
</div>
</div>
)
}
export default Datepicker
import React, { Component, useState,useEffect } from 'react'
import Select from 'react-select'
import { apiTaskCreate } from './lookup'
import { ActionBtn } from './buttons'
import TodoList from './TodoList'
function TodoForm(props) {
const [newTasks, setNewTasks] = useState([])
const [taskname, SetTaskname] = useState('')
const [Importants, setImportants] = useState({})
const [TimeComplete, setTimeComplete] = useState({})
const date_of_task = props.date
const handleChange = e => {
SetTaskname(e.target.value)
}
function onChangeImportants(value){
setImportants(value.value)
}
function onChangeTimeComplete(value){
setTimeComplete(value.value)
}
const handleSubmit = e =>{
e.preventDefault()
SetTaskname('')
let tempNewTasks = [...newTasks]
apiTaskCreate(taskname,Importants,TimeComplete,date_of_task,(response, status)=>{
// console.log(response, status)
if (status === 201){
tempNewTasks.unshift(response)
setNewTasks(tempNewTasks)
} else {
console.log(response)
alert("an error accourd")
}
})
}
const Importants_options = [
{ value: '1', label: 1 },
{ value: '2', label: 2 },
{ value: '3', label: 3 },
{ value: '4', label: 4 },
{ value: '5', label: 5 },
]
const Time_options = [
{ value: '1', label: 30 },
{ value: '2', label: 60 },
{ value: '3', label: 90 },
{ value: '4', label: 120 },
{ value: '5', label: 150 },
{ value: '6', label: 180 },
]
return (
<div className={props.className}>
<div className='col-11 mb-3'>
<form className='todo-form mb-3' onSubmit={handleSubmit}>
<input type='text' value={taskname} placeholder='Task Name'
name='task_name' className='todo-input' onChange={handleChange}></input>
<Select onChange={onChangeImportants} options={Importants_options} placeholder="Importants Score"/>
<Select onChange={onChangeTimeComplete} options={Time_options} placeholder="Time to complete"/>
<button className='btn btn-primary'>Submit</button>
<ActionBtn action={{type: 'optimize', display:"Optimize"}}/>
</form>
</div>
<div className='container'>
<TodoList newTasks={newTasks} {...props}/>
</div>
</div>
)
}
export default TodoForm
import React, {useState, useEffect} from 'react'
import { apiTaskList } from './lookup'
import Task from './Task'
function TodoList(props) {
const [tasksInit, setTasksInit] = useState([])
const [tasks, setTasks] = useState([])
const [tasksDidSet, setTasksDidSet] = useState(false)
// const initialDate = new Date(Date.now())
function join(t, a, s) {
function format(m) {
let f = new Intl.DateTimeFormat('en', m);
return f.format(t);
}
return a.map(format).join(s);
}
let a = [{year: 'numeric'},{month: 'numeric'},{day: 'numeric'}];
const initialDate = join(new Date, a, '-');
const [date, setDate] = useState(initialDate)
// `${initialDate.getFullYear()}-${initialDate.getMonth()+1}-${initialDate.getDate()}`
useEffect( () =>{
const final = [...props.newTasks].concat(tasksInit);
setTasks(tasks => {
if (final.length !== tasks.length) {
return final;
}
return tasks
});
}, [props.newTasks, tasksInit])
useEffect(() => {
if (tasksDidSet === false) {
const handleTasksListLookup = (response, status) => {
if (status === 200) {
setTasksInit(response);
setDate(props.date);
}
}
apiTaskList("admin", date ,handleTasksListLookup)
}
}, [setTasksInit, props.date, tasksDidSet])
return tasks.map((item, index)=>{
return <Task task={item} className='d-flex p-2 justify-content-between border bg-white text-dark' key={`${index}-${item.id}`}/>
})
}
export default TodoList;
import { backendlookup } from "../lookup/lookup";
export function apiTaskCreate(newTask_Name,newImportans_Score,newTime_to_complete,new_date_of_task,callback) {
backendlookup('POST', 'create',callback, {
Task_name: newTask_Name,
Importants_Score: newImportans_Score,
Time_to_Finish: newTime_to_complete,
date_of_task: new_date_of_task,
})
}
export function apiTaskList(username,date,callback) {
let endpoint = 'tasks'
if (date){
endpoint = `tasks?username=${username}&date=${date}`
}
backendlookup('GET', endpoint ,callback)
}
export function apiPartyActionOptimize(action,callback) {
backendlookup('POST', 'action-optimize',callback, {action:action})

Default value is not selected with react-select (4.3.1) using React Hooks

I am trying to auto-selected a value from a list of data in the selected component. Kindly help.
have already tried with the isLoading flag as well.
If the selected value is available in the list then auto selection
if value not available then no issue.
import React, {useEffect, useState} from 'react';
import Select from 'react-select';
import './App.css';
function App() {
const [selectCity, setSelectCity] = useState(null);
const [cityOptions, setCityOptions] = useState([]);
useEffect(() => {
setSelectCity("Mumbai");
setCityOptions([{label: "Kolkata", value:"Kolkata"}, {label: "New Delhi", value:"New Delhi"}, {label: "Chennai", value:"Chennai"}, {label: "Mumbai", value:"Mumbai"}])
}, []);
const onCitySelect = (e) => {
console.log("Selected: ", e);
};
return (
<div className="App">
<Select
defaultValue={selectCity}
options={cityOptions}
onChange={onCitySelect}
/>
</div>
);
}
export default App;
Please pass object "setSelectCity({ label: "Kolkata", value: "Kolkata" });"
import './App.css';
import React, { useEffect, useState } from 'react';
import Select from 'react-select';
const App = () => {
const [selectCity, setSelectCity] = useState(null);
const [cityOptions, setCityOptions] = useState([]);
useEffect(() => {
setSelectCity({ label: "Kolkata", value: "Kolkata" });
setCityOptions([{ label: "Kolkata", value: "Kolkata" }, { label: "New Delhi", value: "New Delhi" }, { label: "Chennai", value: "Chennai" }, { label: "Mumbai", value: "Mumbai" }])
}, []);
const onCitySelect = (e) => {
console.log("Selected: ", e);
setSelectCity(e);
};
return (
<div className="App">
<h1>Hello MERN !!</h1>
<Select
value={selectCity}
options={cityOptions}
onChange={onCitySelect}
/>
</div>
);
}
export default App;
Try using the key prop
<Select
defaultValue={selectCity}
options={cityOptions}
onChange={onCitySelect}
key={selectCity}
/>
The defaultValue props cannot be set dynamically, so you have to set it manually. And please note that the defaultValue should be an object containing the label and the actual value.
import ReactDOM from "react-dom";
import React, { useEffect, useState } from "react";
import Select from "react-select";
function SelectMod() {
const [selectCity, setSelectCity] = useState(null);
const [cityOptions, setCityOptions] = useState([]);
useEffect(() => {
setCityOptions([
{ label: "Kolkata", value: "Kolkata" },
{ label: "New Delhi", value: "New Delhi" },
{ label: "Chennai", value: "Chennai" },
{ label: "Mumbai", value: "Mumbai" }
]);
}, []);
const onCitySelect = (e) => {
console.log("Selected: ", e);
};
return (
<div className="App">
<Select
defaultValue={{ label: "Mumbai", value: "Mumbai" }}
options={cityOptions}
onChange={onCitySelect}
/>
</div>
);
}
export default SelectMod;
const rootElement = document.getElementById("root");
ReactDOM.render(<SelectMod />, rootElement);
Or just set it as the default state value.
const [selectCity, setSelectCity] = useState({ label: "Mumbai", value: "Mumbai" });
--snips--
defaultValue={selectCity}

React calls api thousands of times inside a useEffect

I am building a ToDoList with React and a Django rest Api but I am also using a Datepicker to render all the tasks for the day by the date created. But every time the site loads the api is called thousands of times. The goal would be to only render the tasks for the specific day when the date is changed or a new task for the day is added and not call the backend constalnly the problem seams to lay at the ToDoList because evertwhere else the props.date is only called once and not in a loop.
import React, { useState } from 'react'
import 'date-fns'
import Grid from '#material-ui/core/Grid'
import DateFnsUtils from '#date-io/date-fns'
import{
MuiPickersUtilsProvider,
KeyboardTimePicker,
KeyboardDatePicker
} from '#material-ui/pickers'
import TodoForm from '../ToDo/TodoForm'
function Datepicker() {
const initialDate = new Date(Date.now())
const [selectDate, setSelectDate] = useState(
`${initialDate.getFullYear()}-${initialDate.getMonth()+1}-${initialDate.getDate()}`
)
const handleDateChange = (date) =>{
setSelectDate(`${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`)
}
return (
<div>
<div>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container justify='space-around'>
<KeyboardDatePicker
disableToolbar
varient='inline'
format='MM/dd/yy'
margin='normal'
id='date-picker'
label='Pick your Date'
value={selectDate}
onChange={handleDateChange}
KeyboradButtonProps={{
'aris-label': 'change date'
}}
/>
</Grid>
</MuiPickersUtilsProvider>
</div>
<div>
<TodoForm date={selectDate}/>
</div>
</div>
)
}
export default Datepicker
import React, { Component, useState,useEffect } from 'react'
import Select from 'react-select'
import { apiTaskCreate } from './lookup'
import { ActionBtn } from './buttons'
import TodoList from './TodoList'
function TodoForm(props) {
const [newTasks, setNewTasks] = useState([])
const [taskname, SetTaskname] = useState('')
const [Importants, setImportants] = useState({})
const [TimeComplete, setTimeComplete] = useState({})
const handleChange = e => {
SetTaskname(e.target.value)
}
function onChangeImportants(value){
setImportants(value.value)
}
function onChangeTimeComplete(value){
setTimeComplete(value.value)
}
const handleSubmit = e =>{
e.preventDefault()
SetTaskname('')
let tempNewTasks = [...newTasks]
apiTaskCreate(taskname,Importants,TimeComplete,(response, status)=>{
// console.log(response, status)
if (status === 201){
tempNewTasks.unshift(response)
setNewTasks(tempNewTasks)
} else {
console.log(response)
alert("an error accourd")
}
})
}
const Importants_options = [
{ value: '1', label: 1 },
{ value: '2', label: 2 },
{ value: '3', label: 3 },
{ value: '4', label: 4 },
{ value: '5', label: 5 },
]
const Time_options = [
{ value: '1', label: 30 },
{ value: '2', label: 60 },
{ value: '3', label: 90 },
{ value: '4', label: 120 },
{ value: '5', label: 150 },
{ value: '6', label: 180 },
]
return (
<div className={props.className}>
<div className='col-11 mb-3'>
<form className='todo-form mb-3' onSubmit={handleSubmit}>
<input type='text' value={taskname} placeholder='Task Name'
name='task_name' className='todo-input' onChange={handleChange}></input>
<Select onChange={onChangeImportants} options={Importants_options} placeholder="Importants Score"/>
<Select onChange={onChangeTimeComplete} options={Time_options} placeholder="Time to complete"/>
<button className='btn btn-primary'>Submit</button>
<ActionBtn action={{type: 'optimize', display:"Optimize"}}/>
</form>
</div>
<div className='container'>
<TodoList newTasks={newTasks} {...props}/>
</div>
</div>
)
}
export default TodoForm
import React, {useState, useEffect} from 'react'
import { apiTaskList } from './lookup'
import Task from './Task'
function TodoList(props) {
const [tasksInit, setTasksInit] = useState([])
const [tasks, setTasks] = useState([])
const [tasksDidSet, setTasksDidSet] = useState(false)
const initialDate = new Date(Date.now())
const [date, setDate] = useState("2021-04-12")
// `${initialDate.getFullYear()}-${initialDate.getMonth()+1}-${initialDate.getDate()}`
useEffect( () =>{
const final = [...props.newTasks].concat(tasksInit)
if (final.length !== tasks.length) {
setTasks(final)
}
}, [props.newTasks, tasks, tasksInit])
useEffect(() => {
if (tasksDidSet === false) {
const handleTasksListLookup = (response, status) => {
if (status === 200) {
setTasksInit(response)
setDate(props.date)
console.log(date)
}
}
apiTaskList("admin", date ,handleTasksListLookup)
}
}, [tasksInit, setTasksDidSet, setTasksDidSet, date])
return tasks.map((item, index)=>{
return <Task task={item} className='d-flex p-2 justify-content-between border bg-white text-dark' key={`${index}-${item.id}`}/>
})
}
export default TodoList;
import { backendlookup } from "../lookup/lookup";
export function apiTaskCreate(newTask_Name,newImportans_Score,newTime_to_complete,callback) {
backendlookup('POST', 'create',callback, {
Task_name: newTask_Name,
Importants_Score: newImportans_Score,
Time_to_Finish: newTime_to_complete,
})
}
export function apiTaskList(username,date,callback) {
let endpoint = 'tasks'
if (date){
endpoint = `tasks?username=${username}&date=${date}`
}
backendlookup('GET', endpoint ,callback)
}
export function apiPartyActionOptimize(action,callback) {
backendlookup('POST', 'action-optimize',callback, {action:action})
You are adding a dependency to useEffect which itself is being updated inside it. If you do so, your useEffect execution will go into an infinite loop.
You can make use of functional version of setState to update the tasks state.
Your updated code will look as follows
useEffect( () =>{
const final = [...props.newTasks].concat(tasksInit);
setTasks(tasks => {
if (final.length !== tasks.length) {
return final;
}
return tasks
});
}, [props.newTasks, tasksInit])
useEffect(() => {
if (tasksDidSet === false) {
const handleTasksListLookup = (response, status) => {
if (status === 200) {
setTasksInit(response);
setDate(props.date);
}
}
apiTaskList("admin", date ,handleTasksListLookup)
}
}, [setTasksInit, props.date, tasksDidSet])
When you call the setTasks method inside the useEffect function it updates the tasks value and because you have the tasks variable as one of the dependencies in the useEffect callback, the API gets called indefinitely. Remove tasks from the useEffect dependency and it should work.

react material-ui mui-datatables onRowSelectionChange ID

This is my react code. I am using the material UI. I am working with ID related events. the full code is provided below.
Here, the index ID is getting automatically generated. The issue has to do with that.
import React, { useState } from "react";
import ReactDOM from "react-dom";
import MUIDataTable from "mui-datatables";
import InputLabel from "#material-ui/core/InputLabel";
import MenuItem from "#material-ui/core/MenuItem";
import FormHelperText from "#material-ui/core/FormHelperText";
import FormControl from "#material-ui/core/FormControl";
import Select from "#material-ui/core/Select";
function Ag() {
const [responsive, setResponsive] = useState("vertical");
const onCellClick = () => {
console.log("sadf");
};
const onRowsDelete = () => {
console.log("remove");
};
const onRowSelectionChange = (ev, ex, ez) => {
console.log(ez);
};
const columns = ["Name", "Title", "Location"];
const options = {
filter: true,
filterType: "dropdown",
responsive,
onCellClick,
onRowsDelete,
onRowSelectionChange,
};
const data = [
{
Id: "1",
Name: "sunder",
Title: "dlamds",
Location: "asdfsa",
},
{
Id: "2",
Name: "cvzx",
Title: "sadfsda",
Location: "sadfsdacv",
},
{
Id: "3",
Name: "dsfas",
Title: "werq",
Location: "ewqrwqe",
},
{
Id: "4",
Name: "wqer",
Title: "gfdsg",
Location: "bvcxb",
},
{
Id: "5",
Name: "ereq",
Title: "qwer",
Location: "sdafas",
},
];
return (
<React.Fragment>
<MUIDataTable
title={"ACME Employee list"}
data={data}
columns={columns}
options={options}
/>
</React.Fragment>
);
}
export default Ag;
I want to get a data ID instead of an index ID that was automatically generated when I clicked.
What should I do?
onRowSelectionChange: (currentSelect, allSelected) => {
const result = allSelected.map(item => { return data.at(item.index) });
const selectedIds = result.map(item => {
return item.id;
});
console.log(selectedIds);
}

How to test function component with a react-data-grid

I have created a data grid with react using React-data-grid (link)
My code is as follows:
import React, { useState } from "react";
import ReactDataGrid from 'react-data-grid';
const ROW_COUNT = 20;
const MIN_WIDTH = 100;
const defaultColumnProperties = {
resizable: true,
sortable: true
};
const columns = [
{
key: "eventTypeNameI18n",
name: "Type",
},
{
key: "nameI18n",
name: "Name",
width: 160
},
{
key: "dateCreated",
name: "Time",
width: 220
},
{
key: "locationNameI18n",
name: "Location",
width: 200
}
].map(col => ({...col, ...defaultColumnProperties}));
const sortRows = (initialRows, sortColumn, sortDirection) => rows => {
const comparer = (a, b) => {
if (sortDirection === "ASC") {
return a[sortColumn] > b[sortColumn] ? 1 : -1;
}
else if (sortDirection === "DESC") {
return a[sortColumn] < b[sortColumn] ? 1 : -1;
}
};
return sortDirection === "NONE" ? initialRows : [...rows].sort(comparer);
};
function DataGrid({initialRows}) {
const [rows, setRows] = useState(initialRows);
return (
<ReactDataGrid
id="EventDataGrid"
columns={columns}
rowGetter={i => rows[i]}
rowsCount={ROW_COUNT}
minColumnWidth={MIN_WIDTH}
onGridSort={(sortColumn, sortDirection) =>
setRows(sortRows(initialRows, sortColumn, sortDirection))
}
/>
);
}
export default DataGrid;
I am new to writing unit tests and have been writing very basic unit tests as of recent. I am wondering what is the best way to test the onGridSort method using Jest/Enzyme
In my tests I currently have the following:
import React from 'react';
import ReactDOM from 'react-dom';
import Enzyme, {mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import EventsGrid from '../EventsGrid';
import sampleData from './sampleData/transformedEventSample';
Enzyme.configure({adapter: new Adapter()});
describe('Tests for <EventDataGrid/>', () => {
it('sort data grid by ascending ', () => {
const wrapper = mount(<EventsGrid initialRows={sampleData}/>);
const instance = wrapper.instance();
jest.spyOn(instance, 'sortRows');
const column = 'eventTypeNameI18n';
const sortDirection = 'ASC';
wrapper.find('#EventDataGrid').at(1).prop('onGridSort')(column, sortDirection);
expect(instance.sortRows).toHaveBeenCalled();
});
it('sort data grid by descending', () => {
const wrapper = mount(<EventsGrid initialRows={sampleData}/>);
const instance = wrapper.instance();
jest.spyOn(instance, 'sortRows');
const column = 'eventTypeNameI18n';
const sortDirection = 'DESC';
wrapper.find('#EventDataGrid').at(1).prop('onGridSort')(column, sortDirection);
expect(instance.sortRows).toHaveBeenCalled();
});
});
I want to test to make sure that the grid is ordered correctly (ordered by ascending/descending)

Resources