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);
}
Related
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
Sandbox Link
I want to display the name of the selected item on the button.
Currently, the button says Select User Name but when someone selects a name, that name should be displayed instead.
Try this , it works for me
const App = () => {
const [itemName, setItemName] = useState("Select User Name");
const items = [
{ key: "1", label: "John" },
{ key: "2", label: "Peepo" },
{ key: "3", label: "Patel" },
{ key: "4", label: "Soukup" }
];
const menu = (
<Menu
items={items}
onClick={({ key }) => {
setItemName(items.find((elm) => elm.key === key).label);
}}
/>
);
You can use this approach of displaying the name on the button. On making an item as an object and passing it to the items params.
import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Menu, Dropdown, Button, Space } from "antd";
const App = () => {
const [itemName, setItemName] = useState("Select User Name");
const items = [
{ key: "1", label: "John" },
{ key: "2", label: "Peepo" },
{ key: "3", label: "Patel" },
{ key: "4", label: "Soukup" }
];
const menu = (
<Menu
items={items}
selectable
onSelect={({ key }) => {
setItemName(items[key - 1].label)
}}
/>
);
return (
<>
<h3>Selected user name should appear on the button</h3>
<Dropdown overlay={menu}>
<Button type="primary">
<Space>{itemName}</Space>
</Button>
</Dropdown>
</>
);
};
export default App;
I am pretty new to using jest and Im trying to test a component that makes a state change which acts upon my global state (using Zustand). Basically im clicking a button and its adding an item to my state.traits. Here is my component code:
import { Flex, useToast } from '#chakra-ui/react'
import { FC } from 'react'
import { useProfileStore } from 'stores/profileStore'
interface DataTrait {
name: string,
id: string
}
type Props = {
trait: DataTrait
}
export const ChipItem: FC<Props> = ({ trait }) => {
const { traits, setTraits } = useProfileStore()
const toast = useToast()
const traitNames = traits.map((trait) => trait.name)
const emptyTraits = traits.filter((trait) => trait.name === "")
const handleClick = (trait: DataTrait) => {
if (!traitNames.includes(trait.name) && emptyTraits.length !== 0) {
let currentItem = traits.filter(trait => trait.name === "")[0]
let items = [...traits]
let item = {position: currentItem.position, id: trait.id, name: trait.name}
items[items.indexOf(currentItem)] = item
setTraits(items)
} else if (emptyTraits.length === 0){
toast({
title: 'Error',
status: 'error',
description: 'Only 5 traits can be selected',
isClosable: true,
duration: 5000
})
} else {
toast({
title: 'Error',
status: 'error',
description: 'Please select unique traits',
isClosable: true,
duration: 5000
})
}
}
return (
traitNames.includes(trait.name) ? (
<Flex mx={4} p={2} cursor="pointer" borderRadius="20px" backgroundColor="green" borderWidth="1px" borderColor="white" textColor="white" onClick={() => handleClick(trait)}>{trait.name}</Flex>
) : (
<Flex mx={4} p={2} cursor="pointer" borderRadius="20px" borderWidth="1px" borderColor="grey" onClick={() => handleClick(trait)}>{trait.name}</Flex>
)
)
}
here is my store code:
import create from 'zustand'
export interface Trait {
position: string,
name: string,
id: string,
}
export type Traits = Trait[]
const initialTraits = [
{position: "0", name: "", id: ""},
{position: "1", name: "", id: ""},
{position: "2", name: "", id: ""},
{position: "3", name: "", id: ""},
{position: "4", name: "", id: ""},
]
export type ProfileStore = {
traits: Traits;
setTraits: (traits: Traits) => void;
clearTraits: () => void;
}
export const useProfileStore = create<ProfileStore>((set) => ({
traits: initialTraits,
setTraits: (traits) => set({ traits }),
clearTraits: () => set({ traits: initialTraits })
}))
and here is my test code:
import React from 'react';
import { ChipItem } from "../../ChipList/ChipItem";
import { act, render, renderHook } from "#testing-library/react";
import { useProfileStore } from "../../../stores/profileStore";
const stubbedTrait = {
name: "Doing Work",
id: "efepofkwpeok"
}
it("displays the trait chip", () => {
const { queryByText } = render(<ChipItem trait={stubbedTrait} />);
expect(queryByText("Doing Work")).toBeTruthy();
})
it("sets the chip information in the store", () => {
act(() => {
const { traits } = renderHook(() => useProfileStore())
const { getByText } = render(<ChipItem trait={stubbedTrait}/>);
getByText(stubbedTrait.name).click()
expect(traits.includes(stubbedTrait)).toBeTruthy()
})
})
whats happening, is that it keeps telling me that renderHook is not a function and traits always comes back undefined. any help would be greatly appreciated!
Currently you must install and import React Testing Hooks separately
The best way to unit test Zustand state changes inside and specific component is not by using Zustand but by mocking the store hook with Jest.
You should create a test case for the Zustand Store using React Hook Testing library and once you verify the hook behaves as expected, then you mock the store with manual traits and setTraits changes.
Once you have the unit tests then you should test the behaviour of the real hook and components together with integration tests.
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}
Can someone explain what setFilters is doing here I don't understand how it's declared and what it's doing. I'm trying to implement react-data-grid. I can get one column to filter but when I select another it overwrites the previously save filter selection.
If someone has an example of setFilter I would really appreciate it.
import React, { useState } from "react";
import ReactDOM from "react-dom";
import ReactDataGrid from "react-data-grid";
import { Toolbar, Data } from "react-data-grid-addons";
import createRowData from "./createRowData";
import "./styles.css";
const defaultColumnProperties = {
filterable: true,
width: 120
};
const selectors = Data.Selectors;
const columns = [
{
key: "street",
name: "Street"
},
{
key: "zipCode",
name: "ZipCode"
},
{
key: "date",
name: "Date"
},
{
key: "jobTitle",
name: "Job Title"
},
{
key: "catchPhrase",
name: "Catch Phrase"
},
{
key: "jobArea",
name: "Job Area"
},
{
key: "jobType",
name: "Job Type"
}
].map(c => ({ ...c, ...defaultColumnProperties }));
const ROW_COUNT = 50;
const handleFilterChange = filter => filters => {
const newFilters = { ...filters };
if (filter.filterTerm) {
newFilters[filter.column.key] = filter;
} else {
delete newFilters[filter.column.key];
}
return newFilters;
};
function getRows(rows, filters) {
return selectors.getRows({ rows, filters });
}
function Example({ rows }) {
const [filters, setFilters] = useState({});
const filteredRows = getRows(rows, filters);
return (
<ReactDataGrid
columns={columns}
rowGetter={i => filteredRows[i]}
rowsCount={filteredRows.length}
minHeight={500}
toolbar={<Toolbar enableFilter={true} />}
onAddFilter={filter => setFilters(handleFilterChange(filter))}
onClearFilters={() => setFilters({})}
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Example rows={createRowData(50)} />, rootElement);