简体   繁体   中英

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?

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>

Create the button inside the div tag

array.map((arr) => (
  <div>{arr} <button>Edit</button></div>
 )
const test = () = {
  const array = ['hello', 'myNameIs']
  return (

  {array.map((item,key) => (
    <div key={item}>{item}</div><button>Edit</button>
  )})
}

You are not using the correct syntax for the arrow function It should be like const test = ()=>{} React component JSX should return one parent container try wrapping it like:

 const Test = () => { const array = ["hello", "myNameIs"]; return ( <> {array.map((arr) => { return ( <> <div>{arr}</div> <button>Edit</button> </> ); })} </> ) }

Here is the working code sandbox link https://codesandbox.io/s/kind-easley-jxiei?file=/src/App.js:57-336

I Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM