score:0
it's one of my test. you should save selected ids and check if the id exists in that array.
const [selectedfaqdataids, setselectedfaqdataids] = usestate([]);
const handleselect = (event, id) => {
const selectedindex = selectedfaqdataids.indexof(id);
let newselectedfaqdataids = [];
if (selectedindex === -1) {
newselectedfaqdataids = newselectedfaqdataids.concat(selectedfaqdataids, id);
} else if (selectedindex === 0) {
newselectedfaqdataids = newselectedfaqdataids.concat(selectedfaqdataids.slice(1));
} else if (selectedindex === selectedfaqdataids.length - 1) {
newselectedfaqdataids = newselectedfaqdataids.concat(selectedfaqdataids.slice(0, -1));
} else if (selectedindex > 0) {
newselectedfaqdataids = newselectedfaqdataids.concat(
selectedfaqdataids.slice(0, selectedindex),
selectedfaqdataids.slice(selectedindex + 1)
);
}
setselectedfaqdataids(newselectedfaqdataids);
};
{faqdatas.map((faqdata) => (
<listitem style={{ cursor: 'pointer' }}>
<listitemicon>
{selectedfaqdataids.indexof(faqdata.id) !== -1}? <addicon /> : <removeicon />}
</listitemicon>
<listitemtext primary={faqdata.question} onclick={(event) => handleselect(event, faqdata.id)} />
</listitem>
))}
score:2
is this what you're looking for?
import { usestate } from "react";
import "./styles.css";
const faqdata = [
{ question: "q1", answer: "a1" },
{ question: "q2", answer: "a2" },
{ question: "q3", answer: "a3" },
{ question: "q4", answer: "a4" }
];
const addicon = () => <span class="icon">+</span>;
const removeicon = () => <span class="icon">☓</span>;
function listitem({ d }) {
const [checked, setchecked] = usestate(false);
return (
<li
onclick={() => {
setchecked(!checked);
}}
>
{checked ? <removeicon /> : <addicon />}
{d.question}
</li>
);
}
function list() {
return (
<ul>
{faqdata.map((d) => {
return <listitem d={d} />;
})}
</ul>
);
}
you can try it out here
the problem with the current approach is that there's only one variable to store the added/removed status of every question. so, when the click boolean updates, it updates the state of all elements.
in the code shared above, the listitem component is responsible for maintaining the added/removed status of each question separately. so, one item in the list can change without affecting the other.
score:3
issue
you are using a single boolean value to store a "clicked" state, and all your mapped ui uses that single state to cue from.
solution
assuming you would like multiple items to be clicked, and also assuming your mapped data is static (i.e. the faqdata
isn't added to, removed from, or sorted) then using the mapped index to toggle the "clicked" state is acceptable. use an object to store "clicked" indices and update the handleclick
callback to toggle the state. for this use case i like to make the callback a curried handler to enclose in scope the value i wish to use in the callback.
const [clickedindex, setclickedindex] = usestate({});
const handleclick = (index) => () => {
setclickedindex(state => ({
...state, // <-- copy previous state
[index]: !state[index] // <-- update value by index key
}));
};
...
<list
style={{
maxheight: 430,
width: 500,
overflow: 'auto',
border: '1px solid black',
}}
>
{faqdata.map((item, index) => (
<listitem style={{ cursor: 'pointer' }}>
<listitemicon>
{clickedindex[index] ? <addicon /> : <removeicon />} // <-- check if index is truthy in clickedindex state
</listitemicon>
<listitemtext
primary={item.question}
onclick={handleclick(index)} // <-- pass index to handler
/>
</listitem>
))}
</list>
Source: stackoverflow.com
Related Query
- How to target single item in list with onClick when mapping JSON array in React
- How to target single item in list with onClick when mapping in ReactJS?
- How to create an image background fade when mapping an array of images with React
- React js useState hook. How to update state of a json object with an a array in it when a checkbox is clicked
- Mapping a nested array from JSON in react with a dropdown list
- How can i target a specific item from a list of array on Hover in React
- How to only target a single item in a UI rendered list in React
- Performance when highlighting item in list with React
- How to specify a key for React children when mapping over an array
- mapping an array of objects and changing the value with on onClick in React
- How to update list of items with Infinite scroll when new item added
- How pass to react list item to function as parameter at onClick
- How to re-render react component when mapping over state that is array of objects
- How to handle recursive array mapping with React components?
- how to map array of images into two images per list item React JS
- Remove a single item from the list with onClick
- loop through an array and show single item at a time with dynamic time duration like setTimeout or SetInterval in react js
- how to revert (last clicked list item) back to its original color when any other item is clicked - react hooks
- How to map array of objects which i need to groupby date property in JSON format with react JS
- When creating buttons for each item in an array in React, how do I pass in unique onClick parameters based on the array value?
- How to focus on a list item with useRef react hook
- How to prevent unnecessary re-renders with React Hooks, function components and function depending on item list
- How to delete a list item with React (function component)
- How to display list of mapped array onClick - React
- In React How can I fetch data and render a single object in a states array without mapping the whole thing?
- How to change all value of items in a list in reactJS when onClick on an item
- How can I make only one list item expand when a button is clicked in React (no hooks)?
- How to deal with a value that might be an array, or might be only a single item react component
- How to get onClick in React to work on a single element with multiple siblings?
- React - Dealing with undefined state when mapping over an array of objects from API
More Query from same tag
- How can I access this information in my react state?
- How to resove label overlapping issue for React Material UI auto complete component
- In React 17 jquery issue?
- Transfer { ..this.props } but exclude certain ones
- using @Html.React in my .net MVC view
- On click strike off items and move those items to the bottom of the list
- how to reduce the height of cell or row in react?
- how to access nested object value of axios request's response in react js
- How do I dispatch the id in redux saga?
- Javascript sorting array quiz
- react-router-redux syncHistoryWithStore crash / passing state with react-router
- React - useEffect block loading page
- ReactJS Image Upload form issues with space in filename
- React Authentication (Auth0) - what is the right way?
- Jest: setTimeout is being called too many times
- Why does my create-react-app have no service workers?
- How can I paint and include a simple loading until the element component renders?
- AWS S3 PresignedPost works locally but fails in production with ERR_CONNECTION_RESET
- String useState Value Is Empty after Storing a Value in an API Response to It
- ReactJS push to state array replaces every exisitng value in array
- Function call and pass value in the same OnClick - React
- How do I get the base64 string in the base64 object?
- React portal event bubbling in the wrong direction
- Get the return value of a springboot api in react
- Why won't my form add a new item to the list?
- How Can I render a list dynamically using react-calendar?
- ReactJs how to know when a component is removed from DOM
- window.addEventListener not updating state on route change when scrollY is not 0
- React componentDidMount - Cannot read property of undefined -
- how to remove + symbol from phone number using reactjs