How do I load data file to state array in react? - javascript

I'm new to react.And I'm trying to load data file to a state array instead of directly placing array of data in the state.Below I've placed the code.But this doesn't display the data.
App.js
import React, { Component } from 'react';
import Projects from './Components/Projects';
import data from './data/data'
class App extends Component {
constructor(){
super();
this.state = {
myArrays: [{data}]
}
}
render() {
return (
<div className="App">
<Projects myArrays = {this.state.myArrays} />
</div>
);
}
}
export default App;
It works if I replace
<Projects myArrays = {this.state.myArrays} /> with <Projects myArrays = {data} />
What is the difference between doing this two? And why doesn't it load data with
<Projects myArrays = {this.state.myArrays} />
Project.js
import React, { Component } from 'react';
class Projects extends Component {
render() {
let projectItems;
projectItems = this.props.myArrays.map((project,i) =>{
return(
<li key = {i}>{project.title}</li>
);
});
return (
<ul>
{projectItems}
</ul>
);
}
}
export default Projects;
data.js
export default [
{
title: "Obama set for first political event since leaving office",
category: "politics"
},
{
title: 'La Liga refuse to accept PSG payment for Barcelona striker Neymar',
category: "sports"
},
{
title: "Virtu Financial closes KCG's European prop trading business",
category: "business"
}
]

The difference between
<Projects myArrays = {this.state.myArrays} />
and
<Projects myArrays = {data} />
is the way you are assigning data to the state
this.state = {
myArrays: [{data}]
}
This will result in this.state.myArrays which looks like
[{data: [
{
title: "Obama set for first political event since leaving office",
category: "politics"
},
{
title: 'La Liga refuse to accept PSG payment for Barcelona striker Neymar',
category: "sports"
},
{
title: "Virtu Financial closes KCG's European prop trading business",
category: "business"
}
]
}]
Replace it with
this.state = {
myArrays: data
}
and your first version will also work

Related

setting state within nested response

I am building a react app and I am setting the state with api of nested response of nested state But the state is not setting the way I want.
response that is receiving from api
[
{
"id": 70,
"title": "feefifef",
"images": [
{
"id": 28,
"text": "First Image"
"blog_id": 70,
},
{
"id": 28,
"text": "First Image",
"blog_id": 70,
}
]
}
]
App.js
class App extends React.Component {
constructor(props){
super(props)
this.state = {
blogs = [
{
id: 0,
title: "",
images: [
{
id:0,
text:""
}
]
}
]
}
}
componentDidMount() {
let data;
axios.get('http://127.0.0.1:8000/api/blogs/').then((res) => {
data = res.data;
this.setState({
blogs: data.map((blog) => {
return Object.assign({}, blog, {
id: blog.id,
title: blog.title,
images: blog.images,
}
})
})
})
}
render() {
const blogs = this.state.blogs.map((blog) => (
<BlogList
id={blog.id}
title={blog.title}
images={blog.images}
/>
))
}
return (
<div>{blogs}</div>
)
}
class BlogList extends React.Component {
constructor(props){
super(props)
}
return (
<div>
Title: {this.props.title}
Images: {this.props.images}
</div>
)
}
What is the problem ?
Images are not showing after Title. I am trying to show all images in BlogList class of every blog.
I have also tried using (in BlogList class)
this.props.images.map((img) => {
return (
<div>
Title: {this.props.title}
Images: {img.text}
</div>
)
}
But it showed me
this.props.images.map is not a function.
then I think the problem is with setting state of images (I may be wrong).
When I tried to print this.props.images then it is showing
0: {id: 28, text: '1111', blog_id: 71}
length: 1
[[Prototype]]: Array(0)
I am new in react, Any help would be much Appreciated. Thank You in Advance
this.props.images is an array and hence you can't use {this.props.images} directly. Other wise you will get an error like this "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead"
You have to use something like this
render() {
return (
<div>
Title: {this.props.title} <br/>
Images:
{this.props.images?.map((image, i) => (
<div key={image.id}>
{image.id}<br/>
{image.text}<br/>
{image.blog_id} <br/>
</div>
))}
</div>
);
}

Trying to turn an array into a list

I have a problem with my function that turns data from an array into a list in different component.
I think the problem is with my lack of understanding where to put document.GetElementById().
I get error document.getElementById(...) is null.
Is it because I try to access specific location before it is rendered? Then how should I access it, maybe it has something to do with component lifecycle? Here is my code:
import React, { Component } from 'react';
import Day from "./day";
import image1 from "./img/eggs.jpg";
class Stuff extends Component {
constructor(props){
super(props);
this.makeList = this.makeList.bind(this);
}
makeList(array) {
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
render() {
const source = {
breakfast: [
{
id: 1,
name: "eggs",
img: image1,
description: "Start a day with delicious and nutricious eggs!",
ingridients: ['2 eggs', 'two slices of toast', 'bacon', 'butter']
},
...
]}
return (
<div>
<Day {...source}
makeList={this.makeList} />
</div>
);
}
}
export default Stuff;
and Day component where React turn an error:
import React, { Component } from 'react';
import "./day.css";
class Day extends Component {
render() {
const appChild = document.getElementById('foo').appendChild(this.props.makeList(this.props.source.breakfast.ingridients));
return (
<div className="displayOne">
<img src= {this.props.breakfast[0].img} alt="eggs" />
<h3>{this.props.breakfast[0].description}</h3>
<div id="foo">
<p>{appChild}</p>
</div>
</div>
);
}
}
export default Day;
Thank you for help and understanding!
you probably should use jsx instead of manipulating the dom directly:
function makeList(array) {
return (
<ul>
(array.map((value, index) => (<li>{value}</li>)
</ul>
)
}
or a full, more optimal, solution would be to create a Breakfast component:
class Stuff extends Component {
constructor(props) {
super(props);
this.source = {
breakfast: [
{
id: 1,
name: "eggs",
img: image1,
description: "Start a day with delicious and nutricious eggs!",
ingridients: ['2 eggs', 'two slices of toast', 'bacon', 'butter']
},
]
}
}
render() {
return (
<div>
<Day source={this.source}></Day>
</div>
);
}
}
class Day extends Component {
render() {
return (
<div className="displayOne">
{this.props.source.breakfast.map((breakfast) => <Breakfast breakfast={breakfast}/>)}
</div>
);
}
}
function Breakfast({breakfast}) {
return (
<div className="displayOne">
<img src={breakfast.img} alt="eggs"/>
<h3>{breakfast.description}</h3>
<ul>
{breakfast.ingridients.map((ingridient) => <li>{ingridient}</li>)}
</ul>
</div>
)
}
<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>
In generall, if you haven't done already. I would advice you to go through the "Getting Started" guide of React to understand the "way of react".
Here is the official "Intro to React": https://reactjs.org/tutorial/tutorial.html

Property 'map' of undefined in React

I'm learning a react course online. When I try to display the list of items from an array using map to display in a child component , I keep getting "cannot read property map of undefined.
Error is thrown while fetching data from users
import React, { Component } from "react";
import ReactDOM from "react-dom";
let userList = [
{ name: "John", age: 24, place: "India" },
{ name: "Henry", age: 24, place: "India" },
{ name: "Ulrich", age: 24, place: "India" }
];
const AppChild = ({ name, age, place, Graduated }) => {
return (
<section>
<p>name: {name}</p>
<p>age: {age}</p>
<p>place: {place}</p>
{/* access the value via props */}
<p>Graduated: {Graduated ? "yes!" : "no!"}</p>
</section>
);
};
export default class App extends Component {
state = {
userExists: true,
isGraduated: true,
loading: true,
};
toggleStatus = () => {
this.setState(prevState => ({
userExists: !prevState.userExists // value : false
}));
};
render() {
const { users } = this.props;
return (
<div>
<h2>Profile</h2>
<h4>
Profile Status is {this.state.userExists ? "Updated" : "Outdated"}
<br />
<button onClick={this.toggleStatus}>Check Status</button>
</h4>
{users.map(user => (
<AppChild
name={user.name}
age={user.age}
place={user.place}
Graduated={this.state.isGraduated} // passing state to child component
/>
))}
</div>
);
}
}
ReactDOM.render(<App users={userList} />, document.getElementById("root"));
To figure out the problem, we follow the bouncing ball. From the error message, I guess that the problem occurs on the line
{users.map(user => (
(You can confirm this from the stack trace given with the error message.)
The error tells you that users is undefined. So we look at the declaration for users:
const { users } = this.props;
Ok, so it is really this.props.users. So we look where this is passed in:
ReactDOM.render(<App users={userList} />, document.getElementById("root"));
Here you are passing the value of userList to a prop named users. However, in the code you show here, there is no variable named userList. This is as far as we can go with the information you have given. You need to find where this variable is declared and initialized to continue solving the problem.
Below is the correct code. In the previous code I was trying to render <App/> in both index.js and App.js. Thanks everyone for helping me out
=>index.js
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
let userList = [
{ name: "John", age: 24, place: "India" },
{ name: "Henry", age: 24, place: "India" },
{ name: "Ulrich", age: 24, place: "India" }
];
ReactDOM.render(<App users={userList} />, document.getElementById("root"));
=> App.js
import React, { Component } from "react";
// child component
const AppChild = ({ name, age, place, Graduated }) => {
return (
<section>
<p>name: {name}</p>
<p>age: {age}</p>
<p>place: {place}</p>
{/* access the value via props */}
<p>Graduated: {Graduated ? "yes!" : "no!"}</p>
</section>
);
};
// parent component
export default class App extends Component {
state = {
userExists: true,
isGraduated: true,
loading: true,
};
toggleStatus = () => {
this.setState(prevState => ({
userExists: !prevState.userExists // value : false
}));
};
render() {
const { users } = this.props;
return (
<div>
<h2>Profile</h2>
<h4>
Profile Status is {this.state.userExists ? "Updated" : "Outdated"}
<br />
<button onClick={this.toggleStatus}>Check Status</button>
</h4>
{users.map((user) => {
return(
<AppChild
name={user.name}
age={user.age}
place={user.place}
Graduated={this.state.isGraduated} // passing state to child component
/>
)})}
</div>
);
}
}
If you try to log users after following line of code
const { users } = this.props;
you'll see users is undefined.
Error message "cannot read property map of undefined" says the same thing, you can not apply map helper on an undefined variable. The map works with arrays

Unable to display API call result to WebPage

I have react App.js page from where i am calling Django Rest API and i am getting response as an array now this array i have nested components and i want that nested component to be listed in my code.
If i can showcase single record given by single person name when i try to do with more than one i am getting following error.
Warning: Each child in an array or iterator should have a unique "key" prop.
Now if i change API URL as below
https://e2isaop.rokuapp.com/api/perns/1
I can able to view data in HTML but when it comes to all persons it fails.
I am sorry i am new react not sure how to iterate over sub array of result.
Kindly guide me here for best practice for this.
Here is API Response in JSON
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"uri": "/api/Persons/1",
"PersonId": 1,
"PersonName": "Nirav Joshi",
"Person_Image": "https://ja.amazonaws.com/media/persons/None/51e1257926f3cb184089c41fa54b8f8e1b65a98f1e35d39e55f2b6b335e83cf4.jpg",
"Person_sex": "M",
"Person_BDate": "2019-04-19",
"Person_CDate": "2019-04-23"
},
{
"uri": "/api/Persons/2",
"PersonId": 2,
"PersonName": "New Joshi",
"Person_Image": "https://ja.amazonaws.com/media/persons/None/cc08baaad2ccc918bc87e14cac01032bade23a0733b4e313088d61ee78d77d64.jpg",
"Person_sex": "F",
"Person_BDate": "2011-11-21",
"Person_CDate": "2019-04-27"
},
]
}
Here is react App.js code.
import React from "react";
import ReactDOM from "react-dom";
import Persons from "./Persons";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
persons: []
};
}
componentDidMount() {
fetch("https://e2isen.okuapp.com/api/psons/")
.then(response => response.json())
.then(data => {
let apipersons;
if (data.isNull) {
apipersons = [];
} else {
apipersons = [data];
console.log(apipersons);
}
this.setState({ persons: apipersons });
});
}
render() {
return (
<div>
<h1>Welcome to PersonAPI</h1>
<div>
{this.state.persons.map(pers => {
return (
<Persons
PersonName={pers.PersonName}
key={pers.PersonId}
Person_Image={pers.Person_Image}
Person_BDate={pers.Person_BDate}
Person_sex={pers.Person_sex}
/>
);
})}
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
It should give me result for Four person with their details
PersonName
PersonImage
PersonBdate
PersonSex
You should do :
// apipersons = [data];
apipersons = data.results

React in Typescript with Semantic: Displaying info in Semantic Dropdown

I have an array data sourcing from a JSON file and I need to display some names in the drop down. I am using Semantic UI Dropdown. How can I achieve this? I was able to get it functioning in react however after rewriting the code to include typescript I am unable to. New to react and typescript. In the Dropdown I have set up options to be this.state.jockeys but no data shows up but console.log(this.state.jockeys) shows me the data. When I click on the dropdown, an empty list (with the right number of rows as my data length but the fields are empty) meaning somehow it's picking up my data but cant it somehow cant be read. How would I get the value and key. That could be the problem.
NB: I want to display login property in the dropdown.
Here's what I have;
import * as React from 'react';
import { Divider, Container, Dropdown } from 'semantic-ui-react';
import 'semantic-ui-css/semantic.min.css';
import 'react-promise';
import { Jockey } from '../Jockey';
const data: JockeyArray[] = require('../../team.json');
import { getUniqueJockeys } from '../../utils/uniqueUtil';
interface Props {
start: boolean;
reset: boolean;
startRandom: boolean;
}
interface JockeyArray {
id: number;
login: string;
avatar_url: string;
}
interface State {
nextRacers: string[];
jockeys: JockeyArray[];
}
// Race Component
export class Race extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
jockeys: data as JockeyArray[],
nextRacers: [],
};
}
handleChange = () => {
}
render() {
const options = data.map(({ id, login }) => ({ key: id, value: login, text: login }));
console.log(options);
return (
<div>
<Divider />
<div className="App-container">
<div className="App-dropdown">
<Container>
<p>Add jockeys to the race in the dropdown below (and click Start)</p>
<Dropdown
placeholder="Select Jockey..."
selection={true}
search={true}
value={}
key={}
options={options}
onClick={this.handleChange}
/>
</Container>
</div>
</div>
</div>
);
}
}
}
Example JSON
[
{
"login": "alvinward",
"id": 18378578,
"avatar_url": "https://avatars3.ttrs",
},
{
"login": "meganswat",
"id": 38345670,
"avatar_url": "https://avatars3.xxx",
},
{
"login": "michaelflinch",
"id": 48378108,
"avatar_url": "https://avatars3.xggj",
},
]

Categories

Resources