1

I need an array of alt strings. I can map the array with name strings, but can't get it to return the "alt". This is what I tried:

const data = [
  { name: "Apple", alt: "Fruit" },
  { name: "Banana", alt: "Fruit" },
  { name: "Potatoe", alt: "Vegetable" },
  { name: "Lentil", alt: "Legume" }];
  <span>
      {data.map(item => {
        return (
         <Button item={item.alt.toUpperCase()}>
         {item}
         </Button>
         );
       })}
  </span>

To get an array of namestrings, this worked:

  <span>
      {data.map(item => {
        return (
         <Button key={item.name} item={item.name.toUpperCase()}>
         {item}
         </Button>
         );
       })}
  </span>

This is the error: TypeError: Cannot read property 'toUpperCase' of undefined

3
  • Is the data being populated from AJAX? Commented Oct 18, 2019 at 5:11
  • you are returning {item} inside button, which is an object. Either return {item.name} or {item.alt} Commented Oct 18, 2019 at 5:17
  • item.alt seems undefined in some places Commented Oct 18, 2019 at 5:19

2 Answers 2

2

I think you are trying to create a button please look below

The below code is modified to use key in map function as each of your record is unique and react keys are useful when working with dynamically created components or when your data are altered . Setting the key value will keep your components uniquely identified after the change and they also help in performance.You can read the below blog it explains well about using keys. https://programmingwithmosh.com/react/why-do-i-need-keys-in-react-lists/

 const data = [
      {id:1, name: "Apple", alt: "Fruit" },
      {id:2 ,name: "Banana", alt: "Fruit" },
      {id:3, name: "Potatoe", alt: "Vegetable" },
      {id:4, name: "Lentil", alt: "Legume" }
    ];
    function App() {
      return (
        <span>
          {data.map((item) => (
            <button key={item.id}>{item.alt.toUpperCase()}</button>
          ))}
        </span>
      );
    }

Use this link it is working here https://codesandbox.io/s/friendly-wave-t117u

Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I need! But I still get this error: TypeError: Cannot read property 'toUpperCase' of undefined...
Hi Mina , Could you open the codesandbox and check.
0

Give this a try:

<span>{
  data.map(
    (item, index) => <button 
      alt={item.alt.toUpperCase()} 
      key={someKeyHere}>
        {item.alt.toUpperCase()}
      </button>)
}</span>

Here's a Working Sample StackBlitz for your ref.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.