1

Doing a course on React, and got confused with one of the problems that I have to solve. I have to finish up the code after {list && and before </ul> in such a way that I map the <li> so that it shows each tip. I confused myself with setting up the map function and in setting up the key properly.

import React, { useState, useEffect } from 'react';
import './Tips.css';

function Tips() {
  useEffect(() => {
    fetch('api').then((res) => {
      return res.json();
    }).then((res) => {
      setList(Object.values(res));  
    })
  }, []);
  const [list, setList] = useState();
  return (
    <div className="tips">
      <ul className="tips__list">
      {list &&  tips.map((item.tip) =>
         return (
          <li key={item.tip} className="tips__item">{item.tip}</li>
        );
      )}
      </ul>
    </div>
  );
}

export default Tips;
5
  • 1
    reactjs.org/docs/lists-and-keys.html#keys Please always check the docs before posting here. Commented Jan 26, 2022 at 19:06
  • 2
    What is tips? Did you mean to do list.map(....? What is the issue? what is your question? Commented Jan 26, 2022 at 19:06
  • what is tips in tips.map function ? Commented Jan 26, 2022 at 19:06
  • 1
    looks like typo list.map(item => ...) Commented Jan 26, 2022 at 19:07
  • Array#map documentation with examples: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 26, 2022 at 19:08

2 Answers 2

3

Your .map() should be called in your list variable.

  return (
    <div className="tips">
      <ul className="tips__list">
        {list &&
          list.map((item) => 
            <li key={item.tip} className="tips__item">
              {item.tip}
            </li>
          )}
      </ul>
    </div>
  );
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this helped solved my problem. Got confused with the map function, which you helped clear up. Will accept your answer when the cool down allows me.
0

Simply add it like this

<li key={item.key}>{item.tip}</li>

1 Comment

While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

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.