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

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

Related

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>

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>

Cannot read property "temp" of undefined

it's my first time here. I'm just starting to learn React and I'm having a little problem creating a weather app. When I try to recall the temp value I get the message: cannot read property "temp" of undefined. I would be very grateful for a hint if someone sees an error. I'm attaching the code
import React, { useState } from "react";
import axios from "axios";
export default function Weather() {
let [city, setCity] = useState("");
let [weather, setWeather] = useState("");
function showWeather(response) {
setWeather(response.data);
}
function handleChange(event) {
setCity(event.target.value);
}
function displayTemperature(event) {
event.preventDefault();
let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=97a9745b0c3a1f932357060a2331ab49&units=metric`;
axios.get(url).then(showWeather);
}
let form = (
<div>
<form onSubmit={displayTemperature}>
<input type="text" onChange={handleChange} />
<input type="submit" value="Search" />
</form>
</div>
);
return (
<div>
{form}
<ul>
<li>Temperature: {weather.main.temp}°C</li>
<li>Description: {weather.weather[0].description}</li>
<li>Humidity: {weather.main.humidity}%</li>
<li>Wind: {weather.wind.speed}km/h</li>
<li>
<img
src={`http://openweathermap.org/img/wn/${weather.weather[0].icon}#2x.png`}
alt=""></img>
</li>
</ul>
</div>
);
}
In the initial state weather is an empty string so before the API hit all the value that you're accessing from weather will be not available so you could use either optional chaining
weather?.main?.humidity
or && operator
weather && Array.isArray(weather) && weather[0].description
Codesandbox
import React, { useState } from "react";
import axios from "axios";
export default function Weather() {
let [city, setCity] = useState("");
let [weather, setWeather] = useState("");
function showWeather(response) {
setWeather(response.data);
}
function handleChange(event) {
setCity(event.target.value);
}
function displayTemperature(event) {
event.preventDefault();
let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=97a9745b0c3a1f932357060a2331ab49&units=metric`;
console.log(url);
axios.get(url).then(showWeather);
}
function getImageIcon(weather) {
const value = weather && Array.isArray(weather) && weather[0].icon;
return value;
}
let form = (
<div>
<form onSubmit={displayTemperature}>
<input type="text" onChange={handleChange} />
<input type="submit" value="Search" />
</form>
</div>
);
return (
<div>
{form}
<ul>
<li>Temperature: {weather?.main?.temp}°C</li>
{weather && Array.isArray(weather) && weather[0]?.description}
<li>
Description:{" "}
{weather && Array.isArray(weather) && weather[0].description}
</li>
<li>Humidity: {weather?.main?.humidity}%</li>
<li>Wind: {weather?.wind?.speed}km/h</li>
<li>
<img
src={`http://openweathermap.org/img/wn/${getImageIcon()}#2x.png`}
alt=""
></img>
</li>
</ul>
</div>
);
}
It is showing the error because in the beginning the value of weather is empty string and you are trying to access the property main.temp from it.
You can solve this by using conditional rendering by showing the list only when weather is not empty.
Also not related to this issue but you should add a catch method in displayTemperature method while fetching the data for error handling.
Here is an example below :
import React, { useState } from "react";
import axios from "axios";
export default function Weather() {
let [city, setCity] = useState("");
let [weather, setWeather] = useState("");
function showWeather(response) {
setWeather(response.data);
}
function handleChange(event) {
setCity(event.target.value);
}
function displayTemperature(event) {
event.preventDefault();
let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=97a9745b0c3a1f932357060a2331ab49&units=metric`;
axios.get(url)
.then(showWeather)
.catch(err => console.log(err));
}
let form = (
<div>
<form onSubmit={displayTemperature}>
<input type="text" onChange={handleChange} />
<input type="submit" value="Search" />
</form>
</div>
);
return (
<div>
{form}
{/* Conditionally rendering the list */}
{weather && (
<ul>
<li>Temperature: {weather.main.temp}°C</li>
<li>Description: {weather.weather[0].description}</li>
<li>Humidity: {weather.main.humidity}%</li>
<li>Wind: {weather.wind.speed}km/h</li>
<li>
<img
src={`http://openweathermap.org/img/wn/${weather.weather[0].icon}#2x.png`}
alt=""></img>
</li>
</ul>
)}
</div>
);
}

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 error index.js:1452 Warning: Each child in an array or iterator should have a unique "key" prop

I am trying to iterate through a store using Mobx in React. Here is my contact.jsx.
import React, { Component } from 'react';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import Jumbotron from '../components/Jumbotron';
import {inject, observer} from 'mobx-react';
#inject('MemberStore')
#observer
class Contact extends Component {
handleSubmit = (e) => {
e.preventDefault();
const member = this.member.value;
const email = this.email.value;
// const email = this.email.value;
this.props.MemberStore.addMember({member, email});
this.member.value = '';
this.email.value = '';
}
render() {
const {MemberStore} = this.props;
return (
<div>
<Navbar />
<Jumbotron title="Contact Page" subtitle="You want to get in touch"/>
<div className="container">
<h2>You have {MemberStore.memberCount} members.</h2>
<form onSubmit={e => this.handleSubmit(e)}>
<input type="text" placeholder="Enter Your Name" ref={input => this.member = input }/>
<div>
<input type="text" placeholder= "Enter Your Email" ref={input => this.email = input }/>
</div>
<button>Submit</button>
</form>
<ul>
{MemberStore.members.map(({member, email}) => (
<li key={member}>
{member}
{email}
</li>
))}
</ul>
</div>
<Footer />
</div>
)
}
}
export default Contact;
Now it is only returning the email and I am getting the following error.
index.js:1452 Warning: Each child in an array or iterator should have a unique "key" prop.
But have I not included that in the map function? Any help would be appreciated.
Below is the code for my memberstore.
import {observable, action, computed} from 'mobx';
class MemberStore {
#observable members = [];
#action addMember({name, email}) {
const existing = this.members;
this.members = existing.concat({name,email});
}
#computed get memberCount() {
return this.members.length;
}
}
const store = new MemberStore();
export default store;
Your members array store items that have two properties: name and email.
In your map function you are using destructuring ({member, email}). There's no member property in the members item. Change member to name (and make sure that each item has unique value for name property if you want to use it as a key).
<ul>
{MemberStore.members.map(({ name, email }, i) => (
<li key={i}>
{name}
{email}
</li>
))}
</ul>
I don't know what is coming in member, it should be the same for ever iterated line, so try it:
<ul>
{MemberStore.members.map(({member, email}, index) => (
<li key={index}>
{member}
{email}
</li>
))}
</ul>

Categories