Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array.map() is returning elements all together in React JS


const test = () = {

const array = ['hello', 'myNameIs']

return (

{
array.map((arr) => (
  <div>{arr}</div>
  <button>Edit</button>
  )
}

)

}

This .map() method is not working as I intended.

With the code, I was trying to get

hello [button]
myNameIs [button]

like this.

But when I actually render the code, I get

hello MynameIs [button]

In this kind of situation, How can I change the .map() statement?

Should I use an index?

like image 294
Aden Lee Avatar asked Aug 14 '26 13:08

Aden Lee


1 Answers

Take a look at below example, I created it almost by your code, it is working as you expected without problem.

function App() {
  const array = ['hello', 'myNameIs'];
  return array.map(item => (
    <div key={item}>
      {item} <button>Edit</button>
    </div>
  ));
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
like image 196
Saeed Shamloo Avatar answered Aug 17 '26 01:08

Saeed Shamloo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!