How to Render this Array in array object - javascript

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>

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 "{}".

React white screen of death, why does commenting out this code fix it?

I'm making a simple react app to take trivia questions and answers from an api and display them as a game.
My development of this app has been running smoothly and updating as per expected, however when I imported a decode function to make the trivia questions present correctly, I noticed that further edits of the code would result in a blank white screen, after commenting out some code I've managed to isolate what code seems to be causing the issue.
App.js
import React from 'react'
import Questions from './Questions'
import { nanoid } from 'nanoid'
import { decode } from 'he'
function App() {
const [tempState, setTempState] = React.useState(false)
const [data, setData] = React.useState({})
React.useEffect(() => {
fetch("https://opentdb.com/api.php?amount=5&category=9&difficulty=medium")
.then(res => res.json())
.then(info => setData(info.results.map(item => {
return {
type: item.type,
question: item.question,
correct_answer: item.correct_answer,
incorrect_answers: item.incorrect_answers,
id: nanoid()
}})))
}, [])
const questionElements = data.map(item => (
<Questions
key={item.id}
type={item.type}
question={item.question}
correct_answer={item.correct_answer}
incorrect_answers={item.incorrect_answers}
/>
))
return (
<main>
<img className="blob--top"
src={require('./blobs.png')}
/>
<img className="blob--bottom"
src={require('./blobs1.png')}
/>
{tempState ?
<div className="quiz--container">
<div>
{questionElements}
</div>
</div> :
<>
<div className="title--container">
<div className="title--init">
<h2 className="title--header">Quizzical</h2>
<h4 className="title--subheader">A battle of the brains</h4>
<button className="game--start"
onClick={() => setTempState(!tempState)}
>
Start quiz</button>
</div>
</div>
</>
}
</main>
);
}
export default App;
Questions.js
import React from 'react'
import { decode } from 'he'
export default function Questions(props) {
return(
<div className="question--container">
<h4>{decode(props.question)}</h4>
<div className="question--items">
<button>{decode(props.correct_answer)}</button>
<button>{decode(props.incorrect_answers[0])}</button>
<button>{decode(props.incorrect_answers[1])}</button>
<button>{decode(props.incorrect_answers[2])}</button>
</div>
</div>
)
}
commenting out the following two code sections in App.js resolves the error
const questionElements = data.map(item => (
<Questions
key={item.id}
type={item.type}
question={item.question}
correct_answer={item.correct_answer}
incorrect_answers={item.incorrect_answers}
/>
))
<div>
{questionElements}
</div>
any ideas on what I'm doing wrong? no error messages show up in react, it just shows a blank white screen.
The blank white screen is caused by the error data.map is not a function, which is caused by your setting default value of the data state to be an empty object while it should be an empty array (so that you can map through).
To fix this error, simply set the default value of data to be an empty array.
const [data, setData] = React.useState([])
Code Sandbox: https://codesandbox.io/embed/inspiring-rhodes-gp5kki?fontsize=14&hidenavigation=1&theme=dark

Issue with list and keys in React JS

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>

React js: How to sort item from API data by ascending and descending

I am fetching data from an API, which includes information about countries. I want to sort the countries by ascending and descending from onClick according their names. For now the order of name's output is in alphabetical order(A-Z). I want to sort it to Z-A from onClick in the name in Header component.
Any help will be appreciated.
Here isthe component I'm fetching data: useCountries
import { useState, useEffect } from 'react'
export default function useCountries(search: string) {
const [data, setData] = useState([])
const [savedCountries, setSavedCountries] = useState([])
const fetchData = () => {
fetch('https://restcountries.eu/rest/v2/all')
.then((res) => res.json())
.then((result) => {
setData(result)
setSavedCountries(result)
})
.catch((err) => console.log('error'))
}
useEffect(() => {
const result = [...savedCountries].filter((item: any) =>
item.name.toLowerCase().includes(search.toLowerCase())
)
setData(result)
}, [search, savedCountries])
useEffect(() => {
fetchData()
}, [])
return [data]
}
Header component
import React from 'react'
import './Header.scss'
export default function Header() {
return (
<div className="header">
<ul className="HeadtableRow">
<li>Flag</li>
<li>Name</li> {/* onClick must work from here */}
<li>Language</li>
<li>Population</li>
<li>Region</li>
</ul>
</div>
)
}
In MainTable I'm mapping through fetched data
import React from 'react'
import Header from '../Header'
import TableRow from '../TableRow'
import './mainTable.scss'
export default function MainTable({ countries }: any) {
return (
<div>
<Header />
<table className="table">
<tbody className="tableBody">
{countries &&
countries.map((country?: any) => (
<TableRow
key={country.name}
flagUrl={country.flag}
countryName={country.name}
languages={country.languages}
population={country.population}
region={country.region}
/>
))}
</tbody>
</table>
</div>
)
}
Hard to give you an answer specific to your code (In your code you don't use any click handler -or- sort method). This is more a freelancer mission to give you an "as is" solution.
https://stackoverflow.com/help/how-to-ask
Related Q / articles:
React : How to sort data in asc and desc in ReactJS
How to toggle on Order in ReactJS
How to make a table in ReactJS sortable?
https://www.smashingmagazine.com/2020/03/sortable-tables-react/
API
If your API support sorting you could use this =>
Call like /countries?sort_by=asc(name)
Hello world
"Hello World" example (I use lodash order_by method). You could take this basic code forward (Add an active class, Use API instead of static data, handle errors, handle immutable data, and so on).
const { useState, useEffect } = React;
/* Data */
const users = [{name: "Bob", id: 1}, {name: "Abie", id: 2}, {name: "Michael", id: 3}, {name: "Zoie", id: 4}, {name: "Omer", id: 5}];
function ListItem(props) {
return <li>{props.value}</li>;
}
function UserList(props) {
const [users, setUsers] = useState(props.users);
function sortUsersByAsc() {
const orderBy = _.orderBy(users, ['name'], ['asc']);
setUsers(orderBy);
}
function sortUsersByDesc() {
const orderBy = _.orderBy(users, ['name'], ['desc']);
setUsers(orderBy);
}
const listItems = users.map((user) =>
<ListItem key={user.id.toString()}
value={user.name} />
);
return (
<div>
<ul>
{listItems}
</ul>
<button onClick={() => sortUsersByAsc()}>Sort List By <b>A to Z</b> ↓</button>
<br/><br/>
<button onClick={() => sortUsersByDesc()}>Sort List By <b>Z to A</b> ↑</button>
</div>
);
}
ReactDOM.render(
<UserList users={users} />,
document.getElementById('root')
);
button{
cursor: pointer;
background: blue; color: white;
}
<div id="root"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
NPM package
One more idea is to use a package like ("build-in" sorting features):
https://www.npmjs.com/package/react-table

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

Categories