how to customize tooltip css - javascript

I use useRef and This is part of my code:
useEffect(() => {
setRange(props.instrument);
let data = getValues(props.instrument);
tooltipRef.current.innerHTML = ReactDOMServer.renderToString(
showTooltip(data.LastTradePrice)
);
},[]);
and
const setRange = (instrument) => {
let tooltip = tooltipRef.current;
const rangeInfo = getValues(instrument);
tooltip.children[0].style.left = `50%`;
tooltip.children[0].children[0].style.fill =
rangeInfo.LastTradePrice > rangeInfo.PreviousDayPrice
? `${theme.palette.color.green}`
: `${theme.palette.color.red}`;
tooltip.setAttribute("title", rangeInfo.LastTradePrice);
}
and
const showTooltip = (data) => {
return (
<ThemeProvider theme={theme}>
<Grid
item
className={classes.currentPrice}
>
<LocationIcon
className={clsx(
classes.currentPriceIcon,
device.isMobile && classes.currentPriceIconMobile
)}
></LocationIcon>
</Grid>
</ThemeProvider>
);
};
and
return (
<Grid item ref={tooltipRef}></Grid >
)
By default, it shows me a tooltip.How can I apply the style I want to this tooltip?
This is the default:
For example, how can I change the tooltip backgroundcolor?

Related

react-select arrow key navigation for submenu

I'm working on adding arrow key functionality to a react-select input dropdown with submenus. I am able to open the submenu, however I don't know how to be able focus an option from the submenu.
As you can see in the image, the submenu parent is selected. And I want to be able to focus the options on the right.
export const CustomOption = () => {
const [showNestedOptions, setShowNestedOptions] = useState(false);
const [subMenuOpen, setSubMenuOpen] = useState(null);
// this is used to give styling when an option is hovered over or chosen with arrow key
const [isFocusedState, setIsFocusedState] = useState(false);
// this basically opens the submenu on ArrowRight keyboard click and gives it isFocusedState(true) which is used to render the SELECTED submenu
const handleKeys = (e: any) => {
if (e.key === 'ArrowRight') {
!props.isMobile && setShowNestedOptions(true);
e.setIsFocusedState(true);
} else if (e.key === 'ArrowLeft') {
!props.isMobile && setShowNestedOptions(false);
e.setIsFocusedState(false);
}
};
useEffect(() => {
window.addEventListener('keydown', handleKeys);
return () => {
return window.removeEventListener('keydown', handleKeys);
};
}, []);
// this does the same but on mouseOver (hover)
const handleMouseOver = (e: any) => {
!props.isMobile && setShowNestedOptions(true);
setIsFocusedState(true);
};
const handleMouseLeave = (e: any) => {
!props.isMobile && setShowNestedOptions(false);
setIsFocusedState(false);
};
return (
<Box>
{props.data.nestedOptions ? (
<Box
onMouseLeave={handleMouseLeave}
onMouseOver={handleMouseOver}
onKeyDown={handleKeys}
onClick={() => setIsFocusedState(!isFocusedState)}
>
<MainOption
renderOption={props.renderOption}
option={props.data}
hasNestedOptions={true}
setSubMenuOpen={() => setSubMenuOpen(props.data.value)}
selectOption={selectOption}
isFocused={isFocusedState}
/>
{showNestedOptions && (
<Box>
{(isFocusedState || props.isFocused) &&
map(props.data.nestedOptions, (nestedOption, index: number) => {
const isFirst = index === 0;
const value = props.getOptionValue?.(nestedOption) || props.value;
const label = props.getOptionLabel?.(nestedOption) || props.label;
const nestedInnerProps = innerProps;
nestedInnerProps.onClick = (e: React.ChangeEvent<HTMLInputElement>) =>
selectOption(props.data.nestedOptions.find((o: SelectOption) => o.label === e.target.textContent));
const optionProps = {
...props,
data: { ...nestedOption, parentValue: subMenuOpen },
value: value,
label: label,
children: label,
innerProps: { ...nestedInnerProps, parentValue: subMenuOpen },
};
// here the submenu is rendered and opened
return (
<Box
key={index}
>
<Option {...optionProps} key={value} isFocused={false}>
<Center>
{label}
</Center>
</Option>
</Box>
);
})}
</Box>
)}
</Box>
) : (
// if there's no submenu, simply render the list of options
<Option {...props}>
<MainOption
isMobile={props.isMobile}
option={props.data}
getOptionValue={props.getOptionValue}
renderOption={props.renderOption}
wrapperOptionArg={props.wrapperOptionArg}
getOptionLabel={props.getOptionLabel}
/>
</Option>
)}
</Box>
);
};
I have tried to add onKeyDown to change the isFocused prop conidtionally, like so but somehow it only works on mouseOver and it sets the condition inappropriately ( for all options, or none at all )
return (
<Box
key={index}
>
<Option
{...optionProps}
key={value}
isFocused={props.data.nestedOptions[0] ? true : false}
<Center>
{label}
</Center>
</Option>
</Box>
Unfortunately there's not much information about this certain keyboard functionality that I was able to find online.
In short, how to focus the first element of a submenu when ArrowRight is already used to open the submenu?

How to create Multi-Level Dropdowns in typescript

I am trying to make the multi-level dropdown list using typescript. My dropdown menu structure is as follows:
-Property
-user_port
-xyz
-man_port
-abc
-Property1
-List
-lmn
-Size
-def
For the above structure I am adding code as follows:
renderaItems = (num: any) : JSX.Element[] => {
const aitems: JSX.Element[] = [];
const adata = this.props.propertyTypeName as unknown as string []
if (aitems != null) {
for (let i = 0; i < adata.length; i++) {
const aAction = ( <DropdownItem key="adata">
{adata ? adata[num] : "Loading..."}
</DropdownItem>);
aitems.push(aAction);
}
}
return aitems;
}
renderAItems = (): JSX.Element[] => {
const Aitems: JSX.Element[] = [];
const Adata = this.props.A as unknown as string[]
if (Adata != null) {
for (let i = 0; i < Adata.length; i++) {
const { isaOpen } = this.state
const AAction = ( <DropdownItem key="Adata">
<Dropdown
onSelect={this.onaSelect}
toggle={
<DropdownToggle id="toggle-id-2" onToggle={this.onaToggle}>
{Adata ? Adata[i] : "Loading..."}
</DropdownToggle>
}
isOpen={isaOpen}
dropdownItems={this.renderaItems(i)}
autoFocus={false}
/>
</DropdownItem>);
Aitems.push(AAction);
}
}
else{
const AAction = ( <DropdownItem key="Adata">NA</DropdownItem>);
Aitems.push(AAction);
}
return Aitems;
}
render() {
const { isAOpen } = this.state;
const header: React.ReactFragment = (
<>
<Title size={BaseSizes.xs} headingLevel={'h1'}>Details</Title>
</>
);
const menuOptions = (
<>
<FlexView column={true}>
<FlexItem>
<Dropdown
onSelect={this.onASelect}
toggle={
<DropdownToggle id="toggle-id-1" onToggle={this.onAToggle}>
A
</DropdownToggle>
}
isOpen={isAOpen}
dropdownItems={this.renderAItems()}
autoFocus={false}
/>
</FlexItem>
</FlexView>
</>
);
return (
<div className={Menu}>
{header}
{menuOptions}
</div>
);
}
}
export const XYZContainer = connect()(XYZ);
I want to display the first dropdown which lists 'Property' and 'Property' with a dropdown option. when we click on 'Property'then it opens 'user_port' and 'man_port' with a dropdown option. Currently, I am able to do it with the above code. After that when I click on 'user_port' then it shows the 'xyz' value but when we click 'user_port' it opens 'xyz' and 'abc' and I want it only open 'xyz'.
For Dropdown, I am used PatthernFly library
https://www.patternfly.org/v4/components/dropdown
Is there any way to do it or another better option for it?
Basically, I want to create a Multi-Level dropdown menu.

React js removing item from paginated array won't update the array unless the page changes

I have a list of records that fills a table and adds a remove button next to each record. When I press the remove button, in the console I can see that the records really did decrease by 1 and the item I selected to be removed is actually removed, but that change won't show on the page in the table itself. What could be the problem?
As you can see in the image below, when I click the remove button, the number or records decreases but the item wont be removed from the table itself.
const AddingTable = () => {
const [records, setRecords] = useState(someRecordsReturnedFromAnAPI);
let filterFn = { fn: items => { return items; } };
let headCells = [...];
const { TblContainer, TblHead, TblPagination, recordsAfterPagingAndSorting } = useTable(records, headCells, filterFn);
function handleRemoveClick(itemList, item) {
const index = itemList.indexOf(item);
itemList.splice(index, 1);
setRecords(itemList);
}
function TableRowWithRemove(props) {
let { itemList, item } = props;
return (
<TableRow>
//... Table cells with records contents
<TableCell>
<button onClick={() => handleRemoveClick(itemList, item)}> Remove </button>
</TableCell>
</TableRow>
)
}
return (
<>
<TblContainer>
<TblHead />
<TableBody>
{
recordsAfterPagingAndSorting().map((item, index) => (
<ConditionalTableRow key={index} item={item} itemList={records} />
))}
</TableBody>
</TblContainer>
<TblPagination />
<ConditionalDiv />
</>
);
}
const TblPagination = () => (
typeof records === 'undefined'?
[]
:
<TablePagination
component="div"
page={page}
rowsPerPageOptions={pages}
rowsPerPage={rowsPerPage}
count={records.length}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}/>
)
const recordsAfterPagingAndSorting = () => {
if (typeof records !== 'undefined') {
return stableSort(filterFn.fn(records), getComparator(order, orderBy))
.slice(page * rowsPerPage, (page + 1) * rowsPerPage)
}
else
return null;
}
if (typeof recordsAfterPagingAndSorting !== 'undefined')
return {
TblContainer,
TblHead,
TblPagination,
recordsAfterPagingAndSorting
}
else
return {
TblContainer,
TblHead,
TblPagination
}
}
try using, since splice doesn't change the address of object.
function handleRemoveClick(itemList, item) {
const index = itemList.indexOf(item);
let newItemList =[...itemList];
newItemList.splice(index, 1);
setRecords(newItemList);
}

Filter treeNodes in Ant Design Tree

I'm using a Searchable Tree component in Ant Design. I would like to filter treeNodes on search. So that if a search value is found, a treeNode is shown. If not, it is hidden (i. e. filtered).
There is a filterTreeNode prop in API. Is it possible to filter treeNodes (hide unrelevant treeNodes from search) with this prop? If not, how can achieve the desired result?
Here is my code for filterTreeNode function:
const filterTreeNode = (node) => {
const title = node.title.props.children[2];
const result = node.key.indexOf(searchValue) !== -1 ? true : false
console.log(searchValue);
console.log(result);
return result;
};
I can see that the result (true or false) is logged in the console, but with the Tree itself nothing happens.
Here is a link to codesandbox and the full code for the component:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Tree, Input } from "antd";
import gData from "./gData.js";
const { Search } = Input;
const dataList = [];
const generateList = (data) => {
for (let i = 0; i < data.length; i++) {
const node = data[i];
const { key } = node;
dataList.push({ key, title: key });
if (node.children) {
generateList(node.children);
}
}
};
generateList(gData);
const getParentKey = (key, tree) => {
let parentKey;
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.children) {
if (node.children.some((item) => item.key === key)) {
parentKey = node.key;
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children);
}
}
}
return parentKey;
};
const SearchTree = () => {
const [expandedKeys, setExpandedKeys] = useState([]);
const [autoExpandParent, setAutoExpandParent] = useState(true);
const [searchValue, setSearchValue] = useState("");
const onExpand = (expandedKeys) => {
setExpandedKeys(expandedKeys);
setAutoExpandParent(false);
};
const onChange = (e) => {
const { value } = e.target;
const expandedKeys = dataList
.map((item) => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.key, gData);
}
return null;
})
.filter((item, i, self) => item && self.indexOf(item) === i);
if (value) {
setExpandedKeys(expandedKeys);
setSearchValue(value);
setAutoExpandParent(true);
} else {
setExpandedKeys([]);
setSearchValue("");
setAutoExpandParent(false);
}
};
const filterTreeNode = (node) => {
const title = node.title.props.children[2];
const result = title.indexOf(searchValue) !== -1 ? true : false;
console.log(searchValue);
console.log(result);
return result;
};
const loop = (data) =>
data.map((item) => {
const index = item.title.indexOf(searchValue);
const beforeStr = item.title.substr(0, index);
const afterStr = item.title.substr(index + searchValue.length);
const title =
index > -1 ? (
<span>
{beforeStr}
<span className="site-tree-search-value">{searchValue}</span>
{afterStr}
</span>
) : (
<span>{item.title}</span>
);
if (item.children) {
return { title, key: item.key, children: loop(item.children) };
}
return {
title,
key: item.key
};
});
return (
<div>
<Search
style={{ marginBottom: 8 }}
placeholder="Search"
onChange={onChange}
/>
<Tree
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
treeData={loop(gData)}
filterTreeNode={filterTreeNode}
/>
</div>
);
};
ReactDOM.render(<SearchTree />, document.getElementById("container"));
As mentioned in the API document, filterTreeNode will highlight tree node, and will not hide it.
filterTreeNode
Defines a function to filter (highlight) treeNodes. When the function returns true, the corresponding treeNode will be highlighted
If you want to hide tree node, you will have to manually filter it first before before passing it to Tree in loop function, something like:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Tree, Input } from "antd";
import gData from "./gData.js";
const { Search } = Input;
const dataList = [];
const generateList = (data) => {
for (let i = 0; i < data.length; i++) {
const node = data[i];
const { key } = node;
dataList.push({ key, title: key });
if (node.children) {
generateList(node.children);
}
}
};
generateList(gData);
const getParentKey = (key, tree) => {
let parentKey;
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.children) {
if (node.children.some((item) => item.key === key)) {
parentKey = node.key;
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children);
}
}
}
return parentKey;
};
const SearchTree = () => {
const [expandedKeys, setExpandedKeys] = useState([]);
const [autoExpandParent, setAutoExpandParent] = useState(true);
const [searchValue, setSearchValue] = useState("");
const [treeData, setTreeData] = useState(gData);
const onExpand = (expandedKeys) => {
setExpandedKeys(expandedKeys);
setAutoExpandParent(false);
};
const onChange = (e) => {
const value = e.target.value?.toLowerCase();
const expandedKeys = dataList
.map((item) => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.key, gData);
}
return null;
})
.filter((item, i, self) => item && self.indexOf(item) === i);
if (value) {
const hasSearchTerm = (n) => n.toLowerCase().indexOf(value) !== -1;
const filterData = (arr) =>
arr?.filter(
(n) => hasSearchTerm(n.title) || filterData(n.children)?.length > 0
);
const filteredData = filterData(gData).map((n) => {
return {
...n,
children: filterData(n.children)
};
});
setTreeData(filteredData);
setExpandedKeys(expandedKeys);
setSearchValue(value);
setAutoExpandParent(true);
} else {
setTreeData(gData);
setExpandedKeys([]);
setSearchValue("");
setAutoExpandParent(false);
}
};
const filterTreeNode = (node) => {
const title = node.title.props.children[2];
const result = title.indexOf(searchValue) !== -1 ? true : false;
console.log(searchValue);
console.log(result);
return result;
};
const loop = (data) =>
data.map((item) => {
const index = item.title.indexOf(searchValue);
const beforeStr = item.title.substr(0, index);
const afterStr = item.title.substr(index + searchValue.length);
const title =
index > -1 ? (
<span>
{beforeStr}
<span className="site-tree-search-value">{searchValue}</span>
{afterStr}
</span>
) : (
<span>{item.title}</span>
);
if (item.children) {
return { title, key: item.key, children: loop(item.children) };
}
return {
title,
key: item.key
};
});
return (
<div>
<Search
style={{ marginBottom: 8 }}
placeholder="Search"
onChange={onChange}
/>
<Tree
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
treeData={loop(treeData)}
filterTreeNode={filterTreeNode}
/>
</div>
);
};
ReactDOM.render(<SearchTree />, document.getElementById("container"));
Couple weeks ago, i had to meet same like this client's enhancement. So how i did it was, we had Search over DirectoryTree and inside tree we rendered the nodes with a function
<DirectoryTree
onExpand={handleOperatorExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onSelect={handleOperatorSelect}
>
{renderTreeNodes(mtoCharts)}
</DirectoryTree>
In search onChange event we saved values to a state, like searchValue. Then searchValue was checked in renderTreeNodes function with regex:
let dynamicRegex = `.*(${searchValue.toUpperCase()}){1}.*`;
if
item.name.match(dynamicRegex)
then we display the node otherwise we dont. SIMPLE !
UPDATE : codes
<Search onChange={handleOperatorChange} />
const handleOperatorChange = e => {
const { value } = e.target;
let temp = value.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()"'+#<>?\\\[\]]/g, '');
setSearchValue(temp);
setAutoExpandParent(true);};
and finally renderTreeNodes :
const renderTreeNodes = data =>
data &&
data instanceof Array &&
data.map(item => {
const title = (
<Highlighter
highlightStyle={{ color: '#f50' }}
searchWords={[searchValue]}
autoEscape={true}
textToHighlight={item.name}
/>
);
if (searchValue) {
let dynamicRegex = `.*(${searchValue.toUpperCase()}){1}.*`;
if (!isEmpty(item.children)) {
// let doesChildrenHaveMatchingName = false;
// item.children.forEach(itemChild => {
// if (itemChild.name.match(dynamicRegex)) {
// doesChildrenHaveMatchingName = true;
// }
// });
// if (doesChildrenHaveMatchingName) {
return (
<TreeNode
className={!item.active ? 'dim-category' : ''}
key={item.code}
title={title}
id={item.id}
code={item.code}
level={item.level}
parentId={item.parentId}
parentReference={item.path}
icon={({ expanded }) => (
<Icon type={expanded ? 'folder-open' : 'folder'} style={{ color: '#32327f' }} />
)}
>
{renderTreeNodes(item.children)}
</TreeNode>
);
// }
}
if (item.name.match(dynamicRegex) || item.path.match(dynamicRegex)) {
return (
<TreeNode
className={item.active ? 'false' : 'dim-category'}
key={item.code}
title={!item.leaf ? title : getMtoTitle(item, title)}
{...(item.leaf ? { leaf: item.leaf } : {})}
id={item.id}
code={item.code}
level={item.level}
parentId={item.parentId}
parentReference={item.path}
icon={({ expanded }) => {
return item.leaf ? (
<Icon type="money-collect" style={{ color: '#47bfa5' }} />
) : (
<Icon type={expanded ? 'folder-open' : 'folder'} style={{ color: '#32327f' }} />
);
}}
/>
);
}
} else {
if (!isEmpty(item.children)) {
return (
<TreeNode
className={!item.active ? 'dim-category' : ''}
key={item.code}
title={title}
id={item.id}
code={item.code}
level={item.level}
parentId={item.parentId}
parentReference={item.path}
icon={({ expanded }) => (
<Icon type={expanded ? 'folder-open' : 'folder'} style={{ color: '#32327f' }} />
)}
>
{renderTreeNodes(item.children)}
</TreeNode>
);
}
return (
<TreeNode
className={item.active ? 'false' : 'dim-category'}
key={item.code}
title={!item.leaf ? title : getMtoTitle(item, title)}
{...(item.leaf ? { leaf: item.leaf } : {})}
id={item.id}
code={item.code}
level={item.level}
parentId={item.parentId}
parentReference={item.path}
icon={({ expanded }) => {
return item.leaf ? (
<Icon type="money-collect" style={{ color: '#47bfa5' }} />
) : (
<Icon type={expanded ? 'folder-open' : 'folder'} style={{ color: '#32327f' }} />
);
}}
/>
);
}
});

React shows last state [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need some help with my code below.
import React, { useState, useEffect } from 'react';
import { Container, Row, Col, ListGroup, Button, InputGroup, FormControl } from 'react-bootstrap';
import FileUpload from './Components/FileUpload'
const MyComponent = () => {
//dump
const importData = {
myFields: ['field1', 'field2','field3','field4'],
exampleData: {
field1: "value1",
field2: "value2",
field3: "value3",
field4: "value4"
},
}
const [currentSelectedField, setCurrentSelectedField] = useState();
const [currentSelectedValue, setCurrentSelectedValue] = useState();
const [selectedFields, setSelectedFields] = useState({})
const [currentItemToEdit, setCurrentItemToEdit] = useState()
const [editValue, setEditValue] = useState('');
const [editKey, setEditKey] = useState('');
const alertDilog = (item) => {
console.log(`You clicked the third ListGroupItem ${item}`);
console.log(selectedFields[item])
let exampleData = importData.exampleData
// console.log(exampleData)
let exampleValue = exampleData[item];
setCurrentSelectedField(item);
let selectedFieldsObject = selectedFields;
console.log(selectedFieldsObject)
selectedFields[item] = item
console.log(selectedFieldsObject)
setSelectedFields(selectedFieldsObject)
// console.log(importProduct)
//console.log(item)
//console.log(exampleValue)
setCurrentSelectedValue(exampleValue)
}
const showExample = (data) => {
if (currentSelectedField) {
if (data) {
return (
<span>Example Data = {data} </span>
)
}
}
else {
return (
<span>You didnt select any field
<br/>
</span>
)
}
}
const checkListData = (item) => {
let flag = 0;
Object.keys(selectedFields).map(function (keyName, keyIndex) {
if (keyName === item) {
flag = 1;
}
})
if (flag === 0) {
return false
} else {
return true
}
}
const selectForEditting = (keyName, value) => {
console.log(keyName)
setCurrentItemToEdit({ key: keyName, value: value })
setEditValue(value)
setEditKey(keyName)
}
const selectToDelete = (keyName, value) => {
let fields = selectedFields;
delete fields[keyName];
console.log(fields)
setSelectedFields(fields);
}
const showselectedItems = () => {
// console.log('render')
// console.log(item)
console.log('existing!')
if (selectedFields) {
// console.log('here')
// console.log(item)
return (
<ListGroup defaultActiveKey="#link1">
{Object.keys(selectedFields).map((keyName, keyIndex)=>
// use keyName to get current key's name
// and a[keyName] to get its value
<ListGroup.Item key={keyIndex} action>
<Container fluid >
<Row>
<Col xs={8}>key : {keyName} <br /> value : {selectedFields[keyName]}</Col>
<Col xs={2}> <Button size="sm" onClick={() => selectForEditting(keyName, selectedFields[keyName])} variant="outline-primary">Edit</Button></Col>
<Col xs={2}> <Button size="sm" onClick={() => selectToDelete(keyName, selectedFields[keyName])} variant="outline-primary">x</Button></Col>
</Row>
</Container>
</ListGroup.Item>
)}
</ListGroup>
)
} else {
return (
<span>No selected Fields</span>
)
}
}
const handleProductEdit = (value) => {
console.log(value)
setEditValue(value)
}
const saveEditfield = (item) => {
console.log('save fields')
console.log(item)
selectedFields[editKey] = editValue
let selectedFieldsObject = item;
Object.keys(selectedFieldsObject).map(function (keyName, keyIndex) {
// use keyName to get current key's name
// and a[keyName] to get its value
if (keyName === editKey) {
selectedFieldsObject[keyName] = editValue
}
})
console.log(selectedFieldsObject)
setSelectedFields(selectedFieldsObject)
}
const showEditArea = () => {
// console.log(currentItemToEdit)
if (currentItemToEdit) {
return (
<div>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Text id="basic-addon1">Value ({editKey}) </InputGroup.Text>
</InputGroup.Prepend>
<FormControl
placeholder="New value"
aria-label="New value"
aria-describedby="basic-addon1"
value={editValue}
onChange={e => handleProductEdit(e.target.value)}
/>
</InputGroup>
<Button onClick={() => saveEditfield(selectedFields)} variant="primary">Save</Button>
</div>
)
}
}
const showMainArea = () => {
return (<div> <Row>
<Col>
{showExample(currentSelectedValue)}
<ListGroup defaultActiveKey="#link1">
{importData.myFields.map(item => {
return (
<ListGroup.Item className={'my-1'} key={item} active={checkListData(item)} onClick={() => alertDilog(item)}>
{item}
</ListGroup.Item>
)
})
}
</ListGroup>
</Col>
<Col>Custom Fields
{showselectedItems()}
</Col>
<Col>Edit Area
{showEditArea()}
</Col>
</Row>
<Button variant="success" className={'my-2 mx-1 '}>Send</Button>
</div>)
}
return (
<Container fluid>
<Row>
<Col>
{JSON.stringify(selectedFields)}
</Col>
</Row>
{showMainArea()}
</Container>)
}
export default MyComponent;
When I click on the "delete" button, I can delete the data from selectedFields. But it doesn't show on screen.
For example:
I clicked value 1
I deleted value 1
I can't see empty object on screen, but when I click value 2
I can see value 2 only on the screen.
When you mutate the state and set it to state, react doesn't re-render your component as it thinks that nothing has changed in your state since the reference is same.
Its recommended that you clone the state before updating it
const selectToDelete = (keyName, value) => {
let fields = {...selectedFields}; // cloning it.
delete fields[keyName]; // Not update the cloned data
console.log(fields)
setSelectedFields(fields); // Now this will trigger a re-render and reflect the change
}

Categories