Get Index on Click of a Mapped Array in React Js

get index on click of a mapped array in react js

Like @sebinq and @Abdelouahed have suggested you can write your button like this:

<Button onClick={(event) => this.displayContent(event, index)}
/>

but doing that means you have already bound the helper function to the

this

of the component [natural behaviour of fat arrow functions].

Or else if you wrote your code like this:

<button onClick={this.handleClick(event, index)}>Click Me!</button>

Then you might need to add this to the constructor

this.handleClick = this.handleClick.bind(this)

As so:

 constructor(props){
super(props)
this.state = {
show: false,
}
this.handleClick = this.handleClick.bind(this)
}

Goodluck!

How can I pass the index from javascript map function to the onclick function?

I am doing this without testing, but you should be able to just pass the index like this.

const onClick = (e, index) => {
e.persist()
console.log(e)
//handleImageClick(productObjects[index])
}

console.log(productObjects)
return (
<Wrapper>
{productObjects.map((productObject,index) => (
<ImageWrapper key={index} src={productObject.image} onClick={(e) => onClick(e, index)}>

</ImageWrapper>
))}
</Wrapper>
)
}

How to properly check the current Index of an array in a React map?

It is the second argument of .map function so:

libros.map((l, idx)

where idx is your i

Here is documentation about it

How to get current value onClick from an array of items in React js?

First - don't call a first param in map method as "i"
if you do map for colors then it is 'color'

Second - You can write:

 <IconButton
icon={<FiCircle fill={i} />}
onClick={() => {
setBackgroundColor(i);
}}
color={i}
/>

and you function setBackgroundColor will get your color when you click on that

Get Index of a Object into mapped array React JS

Pass the index to handleButtonState

<TabButtonItem onClick={()=> handleButtonState(index)}>

Can't send data to a useState array and map the array in React

Just a small update on previously given answers. Put the console log outside the addProduct function. Inside the App function body. Otherwise you won't see the updated addedProducts.

function App() {

...

function addProduct(id) {
document.getElementById(`product_${id}`).style.display = 'none';
setAddedProducts([...addedProducts, products[id]]);
}

console.log(addedProducts)

return (
...
);
}

export default App;

Update your second array as follows. If addedProducts state does contain elements. Then it shouldn't show ''No products in your shopping cart''

        <div className="box2">
{addedProducts.length > 0 ? (
addedProducts.map((product, index) => {
<div key={index}>{product.price}</div>;
})
) : (
<div className="noProducts">No products in your shopping cart</div>
)}
</div>

How to pass the array index value from array mapping to onClick function in React?

You need to call it and pass the id to it like so:

<button onClick={e => handleDelete(book.id)}>delete</button>

Related documentation: Passing Arguments to Event Handlers

And also change the body of the handleDelete to just console.log(bookId) if you like to see the passed id printed on console.

const handleDelete = (bookId) => {
console.log(bookId)
};

Map function is not working properly when I hit onClick

This is happening because you are using wrong logic and you don't specify which submenu should be shown.
First, delete the current state and dont use it.
Then, you should define another state like:

const [selectedMenu, setSelectedMenu] = useState("");

then, define this function:

const handleClick = (title) => {
setSelectedMenu(title);
}

after that, once you click on Box, you should invoke function like this:

 onClick={() => handleClick(item.title)}

consequently, you should write your logic like this:

      <Text>{items.title}</Text>
{item.title === selectedMenu
? items.subMenu?.map((item) => {
return <Text>{item.title}</Text>;
})
: ""}

How to update state of elements from array.map() separately?

Here's an easy way to manage multiple states using an object with its keys representing your cells and the values representing whether it is active or inactive. This is also easy to generalize so if you add more cells then all you have to do is just add it to the initialState & rest of your code should work as is.

function App() {

// const [cellState, setCellState] = useState("inactive");

const initialState = {
bar1: "inactive",
bar2: "inactive",
bar3: "inactive",
bar4: "inactive",
}

const [cellState, SetCellState] = React.useState(initialState);

const handleSetCellState = (key) => {
setCellState({
...cellState,
[key]: "active",
});
};


return (
<div className="App">
<div id="cube-container">
{Cube[0].faces[0].data.map((row) => {
return row.map((cell, index) => {
return (
<img
src={require(`./assets/cube/Square_Cube_Icon/${cell.bg}${
cellState[cell.bg] === "inactive" ? "_Unlit" : "_Partial"
}.png`)}
alt={`${cell.bg} background`}
className="cellItem"
onClick={() => handleSetCellState(cell.bg)}
state={cellState[cell.bg]}
key={index}
/>
);
});
})}
</div>
</div>
);
}


Related Topics



Leave a reply



Submit