How I can add component CountryName and component CountryCapital to component Country ?
Display lists in browser:
Russia
Moscow
France
Paris
data.js
export default [{
id: 1,
name: 'France',
capital: 'Paris',
},
{
id: 2,
name: 'Russia',
capital: 'Moscow'
}];
First component CountryName.js
import React, { Component } from 'react'
class CountryName extends Component {
render() {
const {data} = this.props;
const CountryName = data.map(country => {
return (
<div>
<h2>{country.name}</h2>
</div>
)
})
return (
<div>
{CountryName}
</div>
);
}
}
export default CountryName;
Second component CountryCapital.js
import React, { Component } from 'react'
class CountryCapital extends Component {
render() {
const {data} = this.props;
const CountryCapital = data.map(country => {
return (
<div>
<p>{country.capital}</p>
</div>
)
})
return (
<div>
{CountryCapital}
</div>
);
}
}
export default MovieDescription;
Third component Country.js
import React, { Component } from 'react'
import CountryName from './CountryName';
import CountryCapital from './CountryCapital';
class Country extends Component {
render() {
const {data} = this.props;
const country = data.map(country => {
return (
<li key = {country.id}>
</li>
)
})
return (
<ul>
{Country}
</ul>
);
}
}
export default Country;
App.js
import React, {Component} from 'react';
import Country from './components/Country';
class App extends Component {
render() {
return (
<div>
<Country data={this.props.data}/>
</div>
)
}
}
export default App;
//HTML:
<body>
<div id="root"></div>
</body>`
First of all your components are structured in a way that, it will first list down all country names one by one and then list down country capitals one by one.
Since your requirement is to display Country and its capital as a group (like listed together in each line), you don't need two components. And in your Country component, just call the newly written component to display it as a group.
Something like this will work. Combine CountryName and CountryCapital to a single component (CountryData) like below.
const {data} = this.props;
const CountryData = data.map(country => {
return (
<div>
<div><h2>{country.name}</h2></div>
<div><h2>{country.capital}</h2></div>
</div>
)
})
return (
<div>
{CountryData}
</div>
);
And in your Component Country, call this new component and pass props like:
import CountryData from './CountryData';
......
......
render() {
const {data} = this.props;
return (
<CountryData data={this.props.data} />
);
}
Hope that helps.
Error: JSX elements must be wrapped in an enclosing tag
return (
<div><h2>{country.name}</h2></div>
<div><h2>{country.capital}</h2></div>
^
)
})
Related
I am trying to view data using below sample. my list.js file as below:
import React, { Component } from 'react';
import { Person} from './Person';
export class List extends Component {
render() {
const persons = [
{
name:'Frank',
age:30,
city:'city 01'
},
{
name:'Hameed',
age:25,
city:'city 02'
},
{
name:'Jack',
age:24,
city:'city 03'
}
]
const personList = persons.map(person => <Person person={person}/>)
return <div> {personList} </div>
}
}
My person.js file is as below:
import React, { Component } from 'react';
export function Person (person){
return (
<div>
{person.name}
</div>
);
}
I need to print my array value inside the HTML but still did not render the view. I could not fix this.
My App.js file as below:
import logo from './logo.svg';
import './App.css';
import { List} from './components/List'
function App() {
return (
<div className="App">
<List></List>
</div>
);
}
export default App;
You pass the prop person to each <Person />, but inside the <Person /> component you are not getting it well. Each prop you pass, is getting to the function under the props variable, Try this code:
import React, { Component } from 'react';
export function Person (props){
return (
<div>
{props.person.name}
</div>
);
}
Or, alternatively, using destructuring:
import React, { Component } from 'react';
export function Person ({ person }){
return (
<div>
{person.name}
</div>
);
}
In <Person /> component you wrongly used props, try instead as:
export function Person (props) {
const { person } = props
// ... rest
}
See the difference from Person (person) to Person ({ person }). In the explained solution the person is destructured from props.
person.js
import React, { Component } from 'react';
export const Person = (props) => {
return (
<div>
{props.person.name}
</div>
);
}
or,
import React, { Component } from 'react';
export function Person (props){
return (
<div>
{props.person.name}
</div>
);
}
I am sending as a prop an array of objects. When I console.log(this.props) I get the array of objects, but when I try to assign it to a variable it gives me
TypeError:ninjas is undefined
This is how i send the prop
import React from 'react';
import Ninjas from './Ninjas';
class App extends React.Component {
state = {
ninjas:[
{name:"Ryu",age:"20",belt:"black",key:"1"},
{name:"Yoshi",age:"22",belt:"yellow",key:"2"},
{name:"Mario",age:"25",belt:"white",key:"1"}
]
}
render(){
return (
<div>
<h1>My first React App</h1>
<Ninjas list={ this.state.ninjas }/>
</div>
)
}
}
export default App;
And this is how i recibe it
import React from 'react';
class Ninjas extends React.Component {
render(){
const { ninjas } = this.props;
const ninjasList = ninjas.map(ninja => {
return(
<div className="ninja" key={ ninja.key }>
<div>Name: { ninja.name }</div>
<div>Age: { ninja.age }</div>
<div>Belt: { ninja.belt }</div>
</div>
)
})
return (
<div className="ninja-list">
{ ninjasList }
</div>
);
}
}
export default Ninjas;
<Ninjas list={ this.state.ninjas }/>
I suggest you change this to
<Ninjas ninjas={ this.state.ninjas }/>
Otherwise the name would be list in your child component.
In other words the name of the property you use when rendering the component (here in the render function of App) has to correspond to the name you get from the props object in your child component (here your child component is Ninjas).
You are passing ninjas in your Ninjas component <Ninjas list={ this.state.ninjas }/> using list props. So, you should be using this const { list } = this.props; instead of const { ninjas } = this.props; in your Ninjas Component.
import React from 'react';
class Ninjas extends React.Component {
render(){
const { list } = this.props;
const ninjasList = list.map(ninja => {
return(
<div className="ninja" key={ ninja.key }>
<div>Name: { ninja.name }</div>
<div>Age: { ninja.age }</div>
<div>Belt: { ninja.belt }</div>
</div>
)
})
return (
<div className="ninja-list">
{ ninjasList }
</div>
);
}
}
export default Ninjas;
So i'm currently working on a PokeDex using the PokeApi available online.
The code of the project is as follows:
import React, { Component } from "react";
import PokemonCard from "./PokemonCard";
import "../ui/PokemonList.css";
import axios from "axios";
export const PokemonList = class PokemonList extends Component {
state = {
url: "https://pokeapi.co/api/v2/pokemon/",
pokemon: null
};
async componentDidMount() {
const res = await axios.get(this.state.url);
this.setState({ pokemon: res.data["results"] });
console.log(res);
}
render() {
return <div></div>;
}
};
export const PokeList = () => {
return (
<React.Fragment>
{this.state.pokemon ? (
<section className="poke-list">
{this.state.pokemon.map(pokemon => (
<PokemonCard />
))}
</section>
) : (
<h1>Loading Pokemon</h1>
)}
</React.Fragment>
);
};
As you can see, I have declared a state in the PokemonList Component class, but then I try to call it further down within the variable PokeList. The issue is that the state is not being recognized in PokeList
(I get the error "TypeError: Cannot read property 'state' of undefined" )
How can I go about calling the state that's declared in the class above?
-------------------EDIT-------------------------------
Okay, so I realized something. I have a code for my Dashboard.js that displays my list. Code is as follows
import React, { Component } from "react";
import { PokeList } from "../pokemon/PokemonList";
export default class Dashboard extends Component {
render() {
return (
<div>
<div className="row">
<div className="col">
<PokeList />
</div>
</div>
</div>
);
}
}
When I change the code from PokeList to PokemonList. so it'd be
import React, { Component } from "react";
import { PokemonList } from "../pokemon/PokemonList";
export default class Dashboard extends Component {
render() {
return (
<div>
<div className="row">
<div className="col">
<PokemonList />
</div>
</div>
</div>
);
}
}
I think get a list of 20 pokemon from the Api from
console.log(this.state.pokemon);.
But since I'm not displaying PokeList on the dashboard, then none of the pokemon cards display.
Screenshot of console output
First of all functional components are stateless. If you need to maintain state use class components or hooks. You can't use the state of one component in another component, You have two options,
Create a parent-child relationship between those components
Use state management libraries(Redux, etc)
There's a little of confusion between your PokemonList and PokeList component. I believe that what you really are looking for is to have just one of those. If you mix the two, you can have a component that controls the view based on the state, in your case, the state is your Pokemon list.
I mixed the two here, so your render method renders "Loading Pokemon" until you get your response back from axios, then when the response is back, it gets that data, updates your state and the state update trigger a re-render.
import React, { Component } from "react";
import PokemonCard from "./PokemonCard";
import axios from "axios";
class PokemonList extends Component {
state = {
url: "https://pokeapi.co/api/v2/pokemon/",
pokemon: null
};
componentDidMount() {
axios.get(this.state.url).then(res => {
this.setState({ pokemon: res.data["results"] });
});
}
render() {
let pokemonList = <h1>Loading Pokemon</h1>;
const pokemons = this.state.pokemon;
if (pokemons) {
pokemonList = (
<section className="poke-list">
<ul>
{pokemons.map(pokemon => (
<PokemonCard pokemon={pokemon} />
))}
</ul>
</section>
);
}
return <React.Fragment>{pokemonList}</React.Fragment>;
}
}
export default PokemonList;
I also created a simple PokemonCard component where I list the result from the API, just to show you that that approach works.
import React from "react";
const pokemonCard = props => {
return (
<li key={props.pokemon.name}>
<a href={props.pokemon.url}>{props.pokemon.name}</a>
</li>
);
};
export default pokemonCard;
You can find the final code, with PokeList and PokemonList now combined into one component called PokemonList here:
Keep in mind that if your render function depends on a certain state, it's probably certain that you should have that state being managed in that component, or passed down from a parent component.
In your example, I noticed you set url inside your state. URL is really not something that will change. It's a constant,so you can easily remove that from your state and place it in a variable and just leave your pokemon list there.
For example:
const url = "https://pokeapi.co/api/v2/pokemon/";
state = {
pokemon: null
};
componentDidMount() {
axios.get(url).then(res => {
this.setState({ pokemon: res.data["results"] });
});
}
import React , { Component } from "react";
import axios from "axios";
//make it as class based component
export default class PokemonList extends Component {
state = {
url: "https://pokeapi.co/api/v2/pokemon/",
pokemon: null
};
async componentDidMount() {
const res = await axios.get(this.state.url);
this.setState({ pokemon: res.data["results"] });
console.log(res);
}
render() {
//check your data here
console.log(this.state.pokemon)
{/*pass data to child*/}
return <div> <PokeList data = { this.state } /> </div>;
}
};
//export this component
export const PokeList = (props) => {
//check your data is coming or not
console.log(props.data)
//access your data from props
return (
<React.Fragment>
{props.data.pokemon ? (
<section className="poke-list">
{props.data.pokemon.map(pokemon => (
pokemon.name
))}
</section>
) : (
<h1>Loading Pokemon</h1>
)}
</React.Fragment>
);
};
You need iterate your your pokelist passing the result from your componentDidMount function to your child component as a prop , then receive your prop in the child component here it's a working codesandbox iterating your pokemon names in the pokeList child component
I am making a basic dropdown selector. I almost had it working when I realized I was setting the state in both the parent and the child so I refactored again to try to simplify it all and put most of the responsibility in one place.
My logic is in the MyDropDown component, then I have a Header component, then the Main which should render it all.
import React from 'react';
class MyDropdown extends React.Component {
render() {
let initialUsers = this.props.state.users;
let alphabetizeUsers = initialUsers
.sort((a, b) => {
return a.name > b.name;
})
.map(obj => {
return (
<option key={obj.id} value={obj.name}>
{obj.name}
</option>
);
});
return <select>{alphabetizeUsers}</select>;
}
}
export default MyDropdown;
Then I have my main component where I do the api call and pass the state into the dropdown component.
import React from 'react';
import MyDropdown from './MyDropdown';
class UserHeader extends React.Component {
state = {
users: []
};
componentDidMount() {
let initialUsers = [];
fetch('http://localhost:3000/users')
.then(response => {
return response.json();
})
.then(data => {
this.setState({ users: data });
});
}
render() {
return <MyDropdown state={this.state} />;
}
}
export default UserHeader;
And finally my Main Component, where I want to show the value from the selected dropdown menu
import React, { Component } from 'react';
import './Main.css';
import MyDropdown from './components/MyDropdown';
import UserHeader from './components/UserHeader';
class Main extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<span className="App-title">SELECT A USER:</span>
<UserHeader />
</header>
<p className="App-intro">
I should get the dropdown value here: {this.state.user}
</p>
</div>
);
}
}
export default Main;
What I tried doing is moving the statement
I should get the dropdown value here: {this.state.policies} .
into the UserHeader component. How do I get the value selected in the child back up to its parent?
Another thing I've tried is adding a handler to the child component
onChange = e => {
this.setState({ selectedUser: e.target.value });
};
and add it to the select... but again not sure how to get this value up to the parent.
return <select onChange={this.onChange}>{alphabetizeUsers}</select>;
The easiest way to pass the value back to the parent component is through a callback.
Try defining and passing in an onChange={this.onChange} to your Main component like so your Main component becomes:
import React, { Component } from 'react';
import './Main.css';
import MyDropdown from './components/MyDropdown';
import UserHeader from './components/UserHeader';
class Main extends Component {
this.state = {
user: null,
}
constructor(props) {
super(props);
this.onChangeUser = this.onChangeUser.bind(this);
}
onChangeUser(newUser) {
this.setState({ user: newUser });
}
render() {
return (
<div className="App">
<header className="App-header">
<span className="App-title">SELECT A USER:</span>
<UserHeader onChangeUser={this.onChangeUser} />
</header>
<p className="App-intro">
I should get the dropdown value here: {this.state.user}
</p>
</div>
);
}
}
export default Main;
Now you are passing in a callback, you can do the same thing with your UserHeader component.
import React from 'react';
import MyDropdown from './MyDropdown';
class UserHeader extends React.Component {
state = {
users: []
};
componentDidMount() {
let initialUsers = [];
fetch('http://localhost:3000/users')
.then(response => {
return response.json();
})
.then(data => {
this.setState({ users: data });
});
}
render() {
return <MyDropdown state={this.state} onChange={this.props.onChangeUser} />;
}
}
export default UserHeader;
And finally, you can now attach this callback to your <select> element.
import React from 'react';
class MyDropdown extends React.Component {
render() {
let initialUsers = this.props.state.users;
let alphabetizeUsers = initialUsers
.sort((a, b) => {
return a.name > b.name;
})
.map(obj => {
return (
<option key={obj.id} value={obj.name}>
{obj.name}
</option>
);
});
return <select onChange={(ev) => this.props.onChange(ev.target.value)}>{alphabetizeUsers}</select>;
}
}
export default MyDropdown;
By defining the onChange on your select element like this, onChange={(ev) => this.props.onChange(ev.target.value)}, you can return the value to the main component and use it in your state.
single.js :
import React, { Component } from 'react';
import Details from '../components/details'
import { ProgressBar } from 'react-materialize';
import { Route, Link } from 'react-router-dom';
const Test = () => (
<div> RENDER PAGE 1</div>
)
class SinglePage extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
}
}
componentDidMount() {
fetch('http://localhost:1337/1')
.then((res) => res.json())
.then((json) => {
this.setState({
data: json,
});
});
}
render() {
const { data } = this.state;
return (
<div>
<h2> SinglePage </h2>
{!data ? (
<ProgressBar />
) : (
<div>
<Details data={data} />
</div>
)}
</div>
);
}
}
export default SinglePage;
details.js :
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Details extends Component {
static propTypes = {
item: PropTypes.shape({
date: PropTypes.string.isRequired,
}).isRequired,
}
render() {
const { item } = this.props;
return (
<div>
<p> {item.date} </p>
</div>
)
}
}
export default Details;
In console, I am getting an error : Warning: Failed prop type: The prop item is marked as required in Details, but its value is undefined.
From this I though my json was not catched but I have an other component which fetch on http://localhost:1337/ , get datas and display them correctly, and going to http://localhost:1337/1 send me a json response so I'm quite confused here.
Additional screenshot :
SinglePage is passing date props with name data as oppose to item that is defined in Details
<Details item={date} />
Also adding init value for date
constructor(props) {
super(props);
this.state = {
date: { date: null },
}
}