React: this.props.item is undefined - javascript

I try to pass an array from one component to another, and from that one to another one, but my item is undefined.
App.js
From that file I try to pass this.state.searchResults to SearchResults component.
import React from 'react';
import './App.css';
import SearchBar from '../SearchBar/SearchBar';
import SearchResults from '../SearchResults/SearchResults';
import Playlist from '../Playlist/Playlist';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
searchResults: [
{name: 'name1', artist: 'artist1', album: 'album1', id: 1},
{name: 'name2', artist: 'artist2', album: 'album2', id: 2},
{name: 'name3', artist: 'artist3', album: 'album3', id: 3}
]
};
}
render() {
return (
<div>
<h1>Ja<span className="highlight">mmm</span>ing</h1>
<div className="App">
<SearchBar />
<div className="App-playlist">
<SearchResults searchResults={this.state.searchResults} />
<Playlist />
</div>
</div>
</div>
);
}
}
export default App;
SearchResults.js
Here I try to pass received this.props.searchResults to TrackList component
import React from 'react';
import './SearchResults.css';
import TrackList from '../Tracklist/Tracklist';
class SearchResults extends React.Component {
render() {
console.log(this.props.searchResults + ' SearchResults');
return(
<div className="SearchResults">
<h2>Results</h2>
<TrackList tracks={this.props.searchResults} />
</div>
);
}
}
export default SearchResults;
TrackList.js
import React from 'react';
import './Tracklist.css';
import Track from '../Track/Track';
class Tracklist extends React.Component {
constructor(props){
super(props);
console.log(props);
}
render() {
return(
<div className="TrackList">
{this.props.track.map(track => <Track track={track} key={track.id} />)}
</div>
);
}
}
export default Tracklist;
However, if I use map method on this.props.tracks, it says that this method cannot be used on undefined. What is wrong?

Try to replace with the below code in TrackList.js
<div className="TrackList">
{this.props.track.map(track => <Track track={track} key={track.id} />)}
</div>
Hope this helps

The problem is here
{this.props.track.map(track => <Track track={track} key={track.id} />)}
it should be tracks not track
{this.props.tracks.map(track => <Track track={track} key={track.id} />)}
Also if you want to share data between components in React direct with follow top-down way via props you can use React Context

Related

Provider tag in react causing blank screen

I am trying to make a webpage using React js and use redux template. I am trying to wrap my component around < Provider >. After wrapping i get a blank page. I tried using React developer tools that too appears blank. here is my code.Here is the error i am getting
Uncaught Error: Expected the reducer to be a function.
at createStore (createStore.js:55:1)
at ./src/index.js (index.js:9:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at startup:7:1
at startup:7:1
Main.js
import Title from './Title'
import Photowall from './Photowall'
import AddPhoto from './AddPhoto'
import { Route } from 'react-router-dom'
class Main extends Component{
constructor(){
super()
this.state= {
posts : [{
id: "0",
description: "beautiful landscape",
imageLink: "https://image.jimcdn.com/app/cms/image/transf/none/path/sa6549607c78f5c11/image/i4eeacaa2dbf12d6d/version/1490299332/most-beautiful-landscapes-in-europe-lofoten-european-best-destinations-copyright-iakov-kalinin.jpg" +
"3919321_1443393332_n.jpg"
}, {
id: "1",
description: "Aliens???",
imageLink: "https://s3.india.com/wp-content/uploads/2017/12/rocket.jpg"
}, {
id: "2",
description: "On a vacation!",
imageLink: "https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/08/24/104670887-VacationExplainsTHUMBWEB.1910x1000.jpg"
}],
}
this.removePhoto=this.removePhoto.bind(this)
}
removePhoto(postRemoved){
console.log(postRemoved.description)
this.setState((state) => ({
posts: state.posts.filter(post => post !== postRemoved)
}))
}
addPhoto(postSubmitted){
this.setState(state => ({
posts:state.posts.concat([postSubmitted])
}))
}
componentDidMount(){
}
componentDidUpdate(prevProps,prevState){
console.log(prevState.posts)
console.log(this.state)
}
render() {
return (
<div>
<Route exact path="/" render={() => (
<div>
<Title title={'Photowall'}/>
<Photowall posts={this.state.posts} onRemovePhoto={this.removePhoto} onNavigate={this.navigate}/>
</div>
)}/>
<Route path="/AddPhoto" render={({history})=>(
<AddPhoto onAddPhoto={(addedPost)=>{
this.addPhoto(addedPost)
history.push('/')
}}/>
)}/>
</div>
)
}
}
export default Main
AddPhoto.js
import React, { Component } from "react"
class AddPhoto extends Component{
constructor(){
super()
this.handleSubmit=this.handleSubmit.bind(this)
}
handleSubmit(event){
event.preventDefault();
const imageLink = event.target.elements.link.value
const description = event.target.elements.description.value
const post = {
id:0,
description:description,
imageLink:imageLink
}
if(description && imageLink){
this.props.onAddPhoto(post)
}
}
render(){
return(
<div>
<h1>Photowall</h1>
<div className="form">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="Link" name="link"/>
<input type="text" placeholder="Description" name="description"/>
<button>Post</button>
</form>
</div>
</div>
)
}
}
export default AddPhoto
Photo.js
import React, {Component} from "react";
import PropTypes from 'prop-types'
function Photo(props){
const post =props.post
return <figure className="figure">
<img className="photo" src={post.imageLink} alt={post.description}/>
<figcaption><p>{post.description}</p></figcaption>
<div className="button-container">
<button className="remove-button" onClick={()=>{
props.onRemovePhoto(post);
}}> Remove </button>
</div>
</figure>
}
Photo.propTypes={
post: PropTypes.object.isRequired,
onRemovePhoto:PropTypes.func.isRequired
}
export default Photo
Photowall.js
import React,{ Component} from 'react'
import Photo from './Photo'
import PropTypes from 'prop-types'
import {Link} from 'react-router-dom'
function Photowall(props){
return <div>
<Link className='addIcon' to='/AddPhoto' ><img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTIgMGMtNi42MjcgMC0xMiA1LjM3My0xMiAxMnM1LjM3MyAxMiAxMiAxMiAxMi01LjM3MyAxMi0xMi01LjM3My0xMi0xMi0xMnptNyAxNGgtNXY1aC00di01aC01di00aDV2LTVoNHY1aDV2NHoiLz48L3N2Zz4="></img> </Link>
{/*<button onClick={props.onNavigate} className='addIcon'> + </button>*/}
<div className='photo-grid'>
{props.posts.map((post, index) => <Photo key={index} post={post} onRemovePhoto={props.onRemovePhoto}/>)}
</div>
</div>
}
Photowall.propTypes={
posts: PropTypes.array.isRequired,
onRemovePhoto:PropTypes.func.isRequired
}
export default Photowall
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Main from './Components/Main'
import './styles/stylesheet.css'
import {BrowserRouter} from 'react-router-dom'
import {createStore} from 'redux'
import rootReducer from './redux/reducer'
import {Provider} from "react-redux";
const store = createStore(rootReducer)
ReactDOM.render(<Provider store={store}><BrowserRouter><Main/></BrowserRouter></Provider>, document.getElementById('root'));
reducer.js
import posts from '../data/posts'
const postReducer = function posts(state = posts,action){
return state
}
export default postReducer

Blank screen after using react <Provider>

I am trying to make a webpage using React js and use redux template. I am trying to wrap my component around < Provider >. After wrapping i get a blank page. I tried using React developer tools that too appears blank. here is my code. I have tried different methods nut none of them works.
Main.js
import Title from './Title'
import Photowall from './Photowall'
import AddPhoto from './AddPhoto'
import { Route } from 'react-router-dom'
class Main extends Component{
constructor(){
super()
this.state= {
posts : [{
id: "0",
description: "beautiful landscape",
imageLink: "https://image.jimcdn.com/app/cms/image/transf/none/path/sa6549607c78f5c11/image/i4eeacaa2dbf12d6d/version/1490299332/most-beautiful-landscapes-in-europe-lofoten-european-best-destinations-copyright-iakov-kalinin.jpg" +
"3919321_1443393332_n.jpg"
}, {
id: "1",
description: "Aliens???",
imageLink: "https://s3.india.com/wp-content/uploads/2017/12/rocket.jpg"
}, {
id: "2",
description: "On a vacation!",
imageLink: "https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/08/24/104670887-VacationExplainsTHUMBWEB.1910x1000.jpg"
}],
}
this.removePhoto=this.removePhoto.bind(this)
}
removePhoto(postRemoved){
console.log(postRemoved.description)
this.setState((state) => ({
posts: state.posts.filter(post => post !== postRemoved)
}))
}
addPhoto(postSubmitted){
this.setState(state => ({
posts:state.posts.concat([postSubmitted])
}))
}
componentDidMount(){
}
componentDidUpdate(prevProps,prevState){
console.log(prevState.posts)
console.log(this.state)
}
render() {
return (
<div>
<Route exact path="/" render={() => (
<div>
<Title title={'Photowall'}/>
<Photowall posts={this.state.posts} onRemovePhoto={this.removePhoto} onNavigate={this.navigate}/>
</div>
)}/>
<Route path="/AddPhoto" render={({history})=>(
<AddPhoto onAddPhoto={(addedPost)=>{
this.addPhoto(addedPost)
history.push('/')
}}/>
)}/>
</div>
)
}
}
export default Main
AddPhoto.js
import React, { Component } from "react"
class AddPhoto extends Component{
constructor(){
super()
this.handleSubmit=this.handleSubmit.bind(this)
}
handleSubmit(event){
event.preventDefault();
const imageLink = event.target.elements.link.value
const description = event.target.elements.description.value
const post = {
id:0,
description:description,
imageLink:imageLink
}
if(description && imageLink){
this.props.onAddPhoto(post)
}
}
render(){
return(
<div>
<h1>Photowall</h1>
<div className="form">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="Link" name="link"/>
<input type="text" placeholder="Description" name="description"/>
<button>Post</button>
</form>
</div>
</div>
)
}
}
export default AddPhoto
Photo.js
import React, {Component} from "react";
import PropTypes from 'prop-types'
function Photo(props){
const post =props.post
return <figure className="figure">
<img className="photo" src={post.imageLink} alt={post.description}/>
<figcaption><p>{post.description}</p></figcaption>
<div className="button-container">
<button className="remove-button" onClick={()=>{
props.onRemovePhoto(post);
}}> Remove </button>
</div>
</figure>
}
Photo.propTypes={
post: PropTypes.object.isRequired,
onRemovePhoto:PropTypes.func.isRequired
}
export default Photo
Photowall.js
import React,{ Component} from 'react'
import Photo from './Photo'
import PropTypes from 'prop-types'
import {Link} from 'react-router-dom'
function Photowall(props){
return <div>
<Link className='addIcon' to='/AddPhoto' ><img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTIgMGMtNi42MjcgMC0xMiA1LjM3My0xMiAxMnM1LjM3MyAxMiAxMiAxMiAxMi01LjM3MyAxMi0xMi01LjM3My0xMi0xMi0xMnptNyAxNGgtNXY1aC00di01aC01di00aDV2LTVoNHY1aDV2NHoiLz48L3N2Zz4="></img> </Link>
{/*<button onClick={props.onNavigate} className='addIcon'> + </button>*/}
<div className='photo-grid'>
{props.posts.map((post, index) => <Photo key={index} post={post} onRemovePhoto={props.onRemovePhoto}/>)}
</div>
</div>
}
Photowall.propTypes={
posts: PropTypes.array.isRequired,
onRemovePhoto:PropTypes.func.isRequired
}
export default Photowall
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Main from './Components/Main'
import './styles/stylesheet.css'
import {BrowserRouter} from 'react-router-dom'
import {createStore} from 'redux'
import rootReducer from './redux/reducer'
import {Provider} from "react-redux";
const store = createStore(rootReducer)
ReactDOM.render(<Provider store={store}><BrowserRouter><Main/></BrowserRouter></Provider>, document.getElementById('root'));
reducer.js
import posts from '../data/posts'
const postReducer = function posts(state = posts,action){
return state
}
export default postReducer

Passing props state props using context api

I want to pass my state value name to another component Context3.js without using props. I have use context api for creating context and through provider I have passed the value.
Now at Context3.js I am trying to consume it but at output screen I am unbale to see my output.
import './App.css';
import Context3 from './Components/Context3';
function App() {
return (
<div className="App">
<Context3/>
</div>
);
}
export default App;
The main component is App.js.
import React, {Component} from 'react';
export const MyContext = React.createContext();
class Context1 extends Component{
state={
name: 'mohammed'
}
render(){
return(
<div>
<MyContext.Provider value={this.state.name}>
</MyContext.Provider>
</div>
)
}
}
export default Context1;
import React, {Component} from 'react';
import { MyContext } from './Context1';
class Context3 extends Component{
render(){
return(
<div>
<MyContext.Consumer>
{
value => <h1> {value} </h1>
}
</MyContext.Consumer>
</div>
)
}
}
export default Context3;
strong text
You need to wrap your children with the ContextProvider (Context1)
import React, {Component} from 'react';
export const MyContext = React.createContext();
class Context1 extends Component{
state={
name: 'mohammed'
}
render(){
return(
<div>
<MyContext.Provider value={this.state.name}>
{this.props.children}
</MyContext.Provider>
</div>
)
}
}
export default Context1;
import './App.css';
import Context1 from './Components/Context1';
import Context3 from './Components/Context3';
function App() {
return (
<div className="App">
<Context1>
<Context3/>
</Context1>
</div>
);
}
export default App;

Filtered Products not re-rendering in react but re-rendering in the state

I am trying to filter products in my products array. the state is showing filtered products but the component is not re-rendering.
import React, { Component } from "react";
import ProductList from "./ProductList";
import styled from "styled-components";
import Search from "./SearchBox";
import { storeProducts } from "../data";
import { Container } from "reactstrap";
export default class Store extends Component {
constructor() {
super();
this.state = {
campaign: storeProducts,
searchfield: ""
};
}
onChange = e => {
this.setState({ searchfield: e.target.value });
console.log(e.target.value);
};
render() {
const searchStore = this.state.campaign.filter(storeProducts => {
return storeProducts.title
.toLowerCase()
.includes(this.state.searchfield.toLowerCase());
});
console.log(searchStore);
return (
<div>
<div className="col-lg-9 col-md-9 col-sm-9 col-6">
<StoreBanner className="banner_area">
<Search onchange={this.onChange}/>
</StoreBanner>
</div>
</div>
</SearchArea>
<ProductList storeProducts={searchStore} />
</div>
);
My product List component is this, i am making use of react context api.
import React, { Component } from "react";
import Product from "./Product";
import Title from "./Title";
import { ProductConsumer } from "../Context";
export default class ProductList extends Component {
render() {
return (
<React.Fragment>
<div className="py-5">
<div className="container">
<Title className="font-weight-bold" name="Our" title=" Products" />
<div className="row">
<ProductConsumer>
{value => {
return value.products.map(product => {
return <Product key={product.id} product={product} />;
});
}}
</ProductConsumer>
</div>
</div>
</div>
</React.Fragment>
);
}
}
when i search, the console shows the correct number of objects in the array but the products do not re-render. please i need help on this, i have been on it for days. Thanks

Variables in React

I've been working with React for the last days, so don't blame me.
But I'm trying to display my full name with a button but I get an error when I d this.
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Val',
surname: 'Vree',
age: 17,
nationality: 'Netherlands'
};
}
render() {
return (
<div>
<Header header={this.state.name} />
<Content content={this.state.surname} />
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<p>I'm {this.props.content}</p>
</div>
);
}
}
export default App;
How can I put multiple variables in the Content class? Sorry for everything, because I been learning it for some days and I don't have some knowledge of React.
you can pass it in a few ways:
<Content content={ `${this.state.name} ${this.state.surname}`} />
or
<Content name={this.state.name} content={this.state.surname} />
and get
class Content extends React.Component {
render() {
return (
<div>
<p>I'm {this.props.name} {this.props.content}</p>
</div>
);
}
}
just add multiple props. if your feeling lazy want just one prop just pass this.state and you can pass the entire object. but this is bad practice generally.
hope this helps
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Val',
surname: 'Vree',
age: 17,
nationality: 'Netherlands'
};
}
render() {
return (
<div>
{/* <Header header={this.state.name} /> */}
<Content
name={this.state.name} //<---- add more props
surname={this.state.surname}
age={this.state.age}
nationality={this.state.nationality}
/>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<p>I'm {this.props.name} {this.props.surname}</p>
<p> I am {this.props.age} and i'm from {this.props.nationality}</p>
</div>
);
}
}
export default App;
When you say variables I think you mean props. You can pass props from a parent component to a child component like so
<ChildComponent propOne={this.state.stateOne} propTwo={this.state.stateTwo} />
Now ChildComponent has access to both of those props passed down from the parent component.
In ChildComponent you can access propOne by doing props.propOne (or this.props.propOne if ChildComponent is a class component).
In your case, you should do
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Val',
surname: 'Vree',
age: 17,
nationality: 'Netherlands'
};
}
render() {
return (
<div>
<Header header={this.state.name} />
<Content name={this.state.name} surname={this.state.surname} />
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<p>I'm {this.props.name} {this.props.surname}</p>
</div>
);
}
}
export default App;

Categories

Resources