Home > Software design >  Unable to access props inside a div?
Unable to access props inside a div?

Time:10-08

I currently have the following code:

const Suggestions = ({ suggestions }) => {
  return (
    suggestions.map((suggestion, i) => <p key={i}>{suggestion}</p>)
  )
}

But I somehow want to be able to render all of the p tags inside a div. So, my final code after the mapping would look something like:

<div className="suggestions">
    <p>suggestion1</p>
    <p>suggestion2</p>
          ...
</div>

So I tried something like this:

const Suggestions = ({ suggestions }) => {
  return (
     <div className="suggestions">
        suggestions.map((suggestion, i) => <p key={i}>{suggestion}</p>)
     </div>
  )
}

But this says suggestions and i isn't defined. Why am I not able to access the prop inside my div element?

CodePudding user response:

You need to wrap your map with curly braces:

const Suggestions = ({ suggestions }) => {
  return (
     <div className="suggestions">
        {suggestions.map((suggestion, i) => <p key={i}>{suggestion}</p>)}
     </div>
  )
}

CodePudding user response:

import React from 'react';

export const Suggestions = ({ suggestions }) => {
  return (
     <div className="suggestions">
      {suggestions && suggestions.map((item, i) => (<p key={i}> {item} </p>))}
     </div>
  )
}

export const App = () => {
  const list = ['test1', 'test2','test3'];
  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <Suggestions suggestions={list} />
    </div>
  );
}
  • Related