Issue with list and keys in React JS - javascript

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;

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>
);

Simply add it like this
<li key={item.key}>{item.tip}</li>

Related

A variable('person') is not defined ? (basic map method, React JS)

I want to render the information contained in an object. So I use the map method like this,
<ul>
{persons.map(person => <li key={person.id}> person.name </li>)}
</ul>
In VS code and console on the browser, there were no error. But in the main screen it display 'person' is not defined. As far as I know, I am executing the map method correctly. How can I fix this ? Here are the rest of the code. How can
App.js
import { useState } from 'react'
const App = () => {
const [persons, setPersons] = useState([
{
name: 'Arto Hellas',
id: 1
}
])
const [newName, setNewName] = useState('')
const addName = (event) => {
event.preventDefault()
const nameObject = {
name: newName,
id: persons.length + 1
}
setPersons(persons.concat(nameObject))
setNewName('')
}
console.log(persons)
const handleNameChange = (event) => {
setNewName(event.target.value)
}
return (
<div>
<h2> Phonebook </h2>
<form onSubmit={addName}>
<div>
name: <input value={newName} onChange={handleNameChange} />
</div>
<div>
<button type="submit"> add </button>
</div>
</form>
<h2> Numbers </h2>
<ul>
{persons.map(person => <li key={person.id}> person.name </li>)}
</ul>
</div>
)
}
export default App
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(<App />)
Mistake with using persone inside <li/>
<li> key={person.id}> {person.name} </li>
And its works. I didint see 'A variable('person') is not defined' in errors
https://codesandbox.io/s/inspiring-thompson-7f6hqj?file=/src/App.js
You need to change person.name to {person.name}
You're missing on minor code details.
<ul>
{persons.map((person) => {
return <li key={person.id}> {person.name} </li>;
})}
</ul>;
Remember to put inside a JSX element the variables of the component between "{}".

How to Render this Array in array object

Hi I want to render this Advice on the screen but I could not do it I tried to map but that didn't helped please help me
import React, { useState, useEffect } from 'react'
export default function UsersData() {
const [Users, setUsers] = useState([{
"slip": {
"id": 41,
"advice": "Don't use Excel or Powerpoint documents for your basic word processing needs."
}
}])
return(
<>
<h2> React Fetch API Example </h2>
<ul>
{/* Not sure what to write here */}
</ul>
</>
)
}
<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>
I tried {Users.map(e=>{e.slip}) but it didn't work.
Using map function you can print whole array and sample code below here.
<ul>
{Users.map((element) => (
<li key={element.slip.id}>{element.slip.advice}</li>
))}
</ul>
It should be as simple as writing a mapping function:
export default function UsersData() {
const [Users, setUsers] = useState([
{
slip: {
id: 41,
advice:
"Don't use Excel or Powerpoint documents for your basic word processing needs.",
},
},
]);
return (
<>
<h2>React Fetch API Example</h2>
<ul>
{Users.map((user) => (
<li key={user.slip.id}>{user.slip.advice}</li>
))}
</ul>
</>
);
}
Here's a sample for your ref.
Use this:
import React, { useState, useEffect } from 'react'
export default function UsersData() {
const [Users, setUsers] = useState([
{
"slip": {
"id": 41,
"advice": "Don't use Excel or Powerpoint documents for your basic word processing needs."
}
}
])
return (
<>
<h2>React Fetch API Example</h2>
<ul>
{Users.map(({slip})=>(
<li key={slip.id}>{slip.advice}</li>
))}
</ul>
</>
)
}
<h2>React Fetch API Example</h2>
<ul>
{Users.map((user) =>
Object.keys(user).map((key) => (
<li>
{user[key].id} - {user[key].advice}
</li>
))
)}
</ul>

React: Have a return statement but "Nothing was returned from render. This usually means a return statement is missing"

I have a component that I'm currently trying to render. I put a return statement but I am still displaying an error.
import React, { useState } from 'react';
import moment from 'moment';
import {FaSpaceShuttle} from 'react-icons/fa';
export const TaskDate = ({ setTaskDate, showTaskDate, setShowTaskDate }) => {
return (
showTaskDate && (
<div className="task-date" data-testid="task-date-overlay">
<ul className="task-date__list">
<li>
<div
onClick={() => {
setShowTaskDate(false);
setTaskDate(moment().format('DD/MM/YYYY'));
}}
>
<span>
<FaSpaceShuttle />
</span>
<span>Today</span>
</div>
</li>
</ul>
</div>
)
);
};
Any help would be appreciated!
The problem is that when showTaskDate is undefined you don't render anything, you simply return undefined.
You can change your return to use conditionals and return null to render nothing if there is no showTaskDate set.
export const TaskDate = ({ setTaskDate, showTaskDate, setShowTaskDate }) => {
return (
showTaskDate ? (
<div className="task-date" data-testid="task-date-overlay">
<ul className="task-date__list">
...
</ul>
</div>
) : null
);
};

React won't render multiple fetched API's to the DOM

Link to CodeSandbox.
I can successfully display Tavares' fetched data to the DOM through a .map statement. However, once I try to load up the second and third players data using the exact same way (they're there, just commented out right now) - under Tavares' .map - I get thrown an error of, "Cannot read property 'map' of undefined", and the first .map (Matthews) after Tavares'.
Trying to figure out why this error is displaying, and why I can't map all three data points to the DOM.
App.JS
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import "./styles.css";
function App() {
// Set initial state for data
const [data, setData] = useState({ tavares: [], matthews: [], marner: [] });
// Fetch data
useEffect(() => {
const fetchData = async () => {
// Grab all players API's
let tavares =
"https://statsapi.web.nhl.com/api/v1/people/8475166?expand=person.stats&stats=yearByYear,careerRegularSeason&expand=stats.team&site=en_nhlCA";
let matthews =
"https://statsapi.web.nhl.com/api/v1/people/8479318?expand=person.stats&stats=yearByYear,careerRegularSeason&expand=stats.team&site=en_nhlCA";
let marner =
"https://statsapi.web.nhl.com/api/v1/people/8478483?expand=person.stats&stats=yearByYear,careerRegularSeason&expand=stats.team&site=en_nhlCA";
// Axios to get all api's
axios
.all([axios.get(tavares), axios.get(matthews), axios.get(marner)])
.then(
axios.spread((tavares, matthews, marner) => {
setData(
{ tavares: [tavares.data.people[0]] },
{ matthews: [matthews.data.people[0]] },
{ marner: [marner.data.people[0]] }
);
console.log("Tavares:", tavares.data.people[0]);
console.log("Matthews:", matthews.data.people[0]);
console.log("Marner:", marner.data.people[0]);
})
);
};
fetchData();
}, []);
return (
<>
<h1>Tavares</h1>
<ul>
{data.tavares.map(item => (
<li key={item.objectID}>
<p>{item.id}</p>
<p>{item.primaryNumber}</p>
</li>
))}
</ul>
{/* <h1>Matthews</h1>
<ul>
{data.matthews.map(item => (
<li key={item.objectID}>
<p>{item.id}</p>
<p>{item.primaryNumber}</p>
</li>
))}
</ul>
<h1>Marner</h1>
<ul>
{data.marner.map(item => (
<li key={item.objectID}>
<p>{item.id}</p>
<p>{item.primaryNumber}</p>
</li>
))}
</ul> */}
</>
);
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You are calling setData with three arguments (three objects with one player each) rather than an object with all players. This means only the first object with only tavares is getting set as your data (try logging your data object before rendering to see).
You are doing:
setData(
{ tavares: [tavares.data.people[0]] },
{ matthews: [matthews.data.people[0]] },
{ marner: [marner.data.people[0]] }
);
When you should be doing:
setData({
tavares: [tavares.data.people[0],
matthews: [matthews.data.people[0]],
marner: [marner.data.people[0]]
});

i is not defined using map() with ES6

Trying to create a li in react but failed. Error is near the map(), I got error of i is not defined, why?
const TodoItems = React.creatClass({
getInitialState() {
return {
items : [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
]
}
},
renderItem(){
return(
<ul>
this.state.items.map(item,i =>
<li key={i}>item.name</li>
)
</ul>
)
},
render(){
return (
<renderItem />
)
}
})
When you have multiple arguments for an arrow function, you need to put () around them. So:
this.state.items.map((item,i) =>
// ------------------^------^
<li key={i}>item.name</li>
)
Your original code calls map with item as its first argument, and an arrow function taking a single argument (i) as its second argument.
You also need to put item.name in {} and put the call to map in {}:
renderItem(){
return(
<ul>
{this.state.items.map((item,i) =>
<li key={i}>{item.name}</li>
)}
</ul>
)
Then it works:
const { Component } = React;
const { render } = ReactDOM;
const TodoItems = React.createClass({
getInitialState() {
return {
items : [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
]
}
},
renderItem(){
return(
<ul>
{this.state.items.map((item,i) =>
<li key={i}>{item.name}</li>
)}
</ul>
)
},
render(){
return this.renderItem();
}
});
render(<TodoItems /> , document.getElementById('items'));
<div id="items"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
That became clear to me when I used Babel's REPL to compile the JSX and realized I was seeing "this.state.map((item,i) =>" as a string.
try this :
renderItem(){
return(
<ul>
{this.state.items.map((item,i) => {
return(
<li key={i}>item.name</li>);
})}
</ul>
)

Categories