I am following a tutorial. I don't get why totalCounters is null. I searched online but I do not understand it.
The error message I get is :
TypeError: Cannot read property 'counters' of null.
I followed the tutorial from Mosh.
This is my App.js file.
import React, { Component } from "react";
import NavBar from "./components/navbar";
import Counters from "./components/counters";
import "./App.css";
class App extends Component {
render() {
return (
<React.Fragment>
<NavBar totalCounters={this.state.counters.length} />
<main className="container">
<Counters
counters={this.counters}
onReset={this.handleReset}
onIncrement={this.handleIncrement}
onDelete={this.handleDelete}
/>
</main>
</React.Fragment>
);
}
}
export default App;
This is my navbar.jsx
import React, { Component } from "react";
class NavBar extends Component {
render() {
return (
<nav className="navbar navbar-light bg-light">
<a className="navbar-brand" href="#">
Navbar <span className="badge badge-pill badge-secondary">{this.props.totalCounters}</span>
</a>
</nav>
);
}
}
export default NavBar;
This is my counters.jsx
import React, { Component } from "react";
import Counter from "./counter";
class counters extends Component {
state = {
counters: [
{ id: 1, value: 5 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleIncrement = counter => {
const countersCopy = [...this.state.counters];
const index = countersCopy.indexOf(counter);
countersCopy[index] = { ...counter };
countersCopy[index].value++;
this.setState({ counters: countersCopy });
};
handleReset = () => {
const resetCounters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: resetCounters });
};
handleDelete = counterId => {
const newCounters = this.state.counters.filter(c => c.id !== counterId);
this.setState({ counters: newCounters });
};
render() {
return (
<div>
<button
onClick={this.handleReset}
className="btn btn-primary btn-sm m2"
>
Reset
</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onDelete={this.props.onDelete}
onIncrement={this.handleIncrement}
counter={counter}
/>
))}
</div>
);
}
}
export default counters;
In React, this.state is local to each component.
So, setting this.state.counters in counters does not allow App component to use the state.
This is why counters is null in App component.
Because you don't have a state field into your App class components.
Everywhere you want to use state, you have to create a state object.
Class field
class App extends Component {
state = { counters: [] }
}
Inside contructor
class App extends Component {
contructor(props) {
super(props)
this.state = { counters: [] }
}
}
You are not initializing the state. Your state is undefined. Fix it like this
class App extends Component {
this.state = { counters : [] }
}
Related
I'm learning React. I'm trying to build a simple todo app on my own to learn & practice with the library. I have passed a list of tasks in the parent component & passed them to the child component as props. I was also able to output it in the child component using the map() method. However, I have no idea how to delete an item. I have tried searching online, but I'm unable to adapt their solutions to my use case.
Parent Component
import React, { Component } from 'react';
import './styles/components/App.css';
import Todos from './components/Todos'
class App extends Component {
state = {
todos: [
{ task: 'Study React', id: 1 },
{ task: 'Build something with it', id: 2 },
{ task: 'Apply for jobs', id: 3 },
],
}
render(){
return (
<div className="App">
<Todos todos={this.state.todos} />
</div>
);
}
}
export default App;
Child Component
import React, { Component } from 'react';
import '../styles/components/Todos.css'
class Todos extends Component {
render() {
let { todos } = this.props;
let todoList = todos.map(( todo => {
return (
<div className="todos" key={todo.id}>
<div>{ todo.task }</div>
</div>
)
}));
return (
<div onClick={this.deleteTask}>{ todoList }</div>
)
}
deleteTask() {
// checks if method is working
console.log('working');
// code to delete
}
}
export default Todos
Parent Component
import React, { Component } from 'react';
import './styles/components/App.css';
import Todos from './components/Todos'
class App extends Component {
state = {
todos: [
{ task: 'Study React', id: 1 },
{ task: 'Build something with it', id: 2 },
{ task: 'Apply for jobs', id: 3 },
],
};
// Event and data put in same Component.
deleteTodo(id) {
let workTodos = [...this.state.todos];
const deleteIndex = workTodos.findIndex(todo => todo.id === id);
workTodos.splice(deleteIndex, 1);
this.setState({
todos: [...workTodos]
})
}
render(){
// Use props give Todos Component the data and events to render dom
return (
<div className="App">
<Todos
todos={this.state.todos}
deleteTodo={this.deleteTodo.bind(this)}
/>
</div>
);
}
}
export default App;
Child Component
import React, { Component } from 'react';
import '../styles/components/Todos.css'
class Todos extends Component {
render() {
// Receiving events and data form props
let { todos, deleteTodo } = this.props;
// Click div trigger deleteTodo, It can execute deleteTodo in App component
return todos.map(( todo => {
return (
<div
className="todos"
key={todo.id}
onClick={() => { deleteTodo(todo.id) }}
>
<div>{ todo.task }</div>
</div>
)
}));
}
}
export default Todos
Like a commit, put delete event in App component, Then use props trigger it in the Todos component, Please let me know if you have any questions.
So I keep div element in my state. I want to change it's className in response to onClick event. I know I could do it with event.target.className but the code below is only the sample of a biggest application and it's not possible to use it there. As a resultant from changeClass function I get
"TypeError: Cannot assign to read only property 'className' of object '#'".
So I wonder is there any other way to do it?
import React, { Component } from "react";
import "./styles/style.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
myDiv: [
<div
id="firstDiv"
key={1}
className={"first"}
onClick={this.changeClass}
/>
]
};
}
changeClass = () => {
this.setState(prevState => {
return { myDiv: (prevState.myDiv[0].props.className = "second") };
});
};
render() {
return <div>{this.state.myDiv.map(div => div)}</div>;
}
}
export default App;
Don't put your jsx in state. only add className and state and onChangeClass use this.stateState to update className.
import React, { Component } from "react";
import "./styles/style.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
className:"first"
};
}
changeClass = () => {
this.setState({ classNmae: "two" });
};
render() {
return <div>
<div
id="firstDiv"
className={this.state.className}
onClick={this.changeClass}
/>
</div>;
}
}
export default App;
there's a simpler option try this:
import React, { Component } from "react";
import "./styles/style.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
className: "first"
};
}
changeClass = () => {
this.setState({className: "second"});
};
render() {
return <div
id="firstDiv"
className={this.state.className}
onClick={this.changeClass}>
</div>;
}
}
export default App;
You can use Hooks if you use a React version upper than 16.8
import React, { useState } from "react"
import "./styles/style.css"
const App = () => {
const [myClass, setMyClass] = useState("first")
const changeClass = () => {
setMyClass("second")
}
render() {
return <div
id="firstDiv"
className={myClass}
onClick={changeClass}>
</div>;
}
}
export default App
I have initiated a state in _app.js using Next.js.
I would like to use this state in the index.js file.
How can I access it?
This is my _app.js code:
import React from 'react';
import App, { Container } from 'next/app';
import Layout from '../components/Layout';
export default class MyApp extends App {
constructor(props) {
super(props);
this.state = {
currencyType: {
name: 'Ether',
price: 1,
},
ethPriceUsd: 1,
};
}
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {};
let ethPriceUsd;
if (Component.getInitialProps) {
fetch(`https://api.coingecko.com/api/v3/coins/ethereum/`)
.then((result) => result.json())
.then((data) => {
ethPriceUsd = parseFloat(data.market_data.current_price.usd).toFixed(
2
);
});
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps, ethPriceUsd };
}
componentDidMount() {
const ethPriceUsd = this.props.ethPriceUsd;
this.setState({ ethPriceUsd });
}
onCurrencyTypeChange(currencyTypeValue) {
let currencyType = {};
//Value comes from Header.js where Ether is 0 and USD is 1
if (currencyTypeValue) {
currencyType = {
name: 'USD',
price: this.state.ethPriceUsd,
};
} else {
currencyType = {
name: 'Ether',
price: 1,
};
}
alert('We pass argument from Child to Parent: ' + currencyType.price);
this.setState({ currencyType });
}
render() {
const { Component, pageProps } = this.props;
return (
<Container>
<Layout changeCurrencyType={this.onCurrencyTypeChange.bind(this)}>
<Component {...pageProps} />
</Layout>
</Container>
);
}
}
A lot of it is irrelevant (Like passing the data to the Layout etc...). All I want to do is use this state in my index.js.
let's say you have this code in _app.js.
import React from 'react'
import App, { Container } from 'next/app'
export default class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
}
state = {
name: "Morgan",
}
render () {
const { Component, pageProps } = this.props
return (
<Container>
<Component {...pageProps} {...this.state}/>
</Container>
)
}
}
Please notice the state and <Component {...pageProps} {...this.state}/>
Solution 1:
Now, let's see how can we use it in index.js or any other pages
import React from 'react';
export default class Index extends React.Component {
render() {
return (
<div>
<h2>My name is {this.props.name}</h2>
</div>
)
}
}
You can use them as props like this this.props.name
Solution 2:
Populate state in the index.js from props and then access it from state
import React from 'react';
export default class Index extends React.Component {
constructor(props) {
super(props)
this.state ={
name: this.props.name
}
}
render() {
return (
<div>
<h2>My name is {this.state.name}</h2>
</div>
)
}
}
You can use them as props like this this.state.name
Task is to fetch data from api when toggle between tags
When click on the link it calls the api service but state of feeds is not updated but it throws below warning
jQuery.Deferred exception: Cannot read property 'setState' of undefined TypeError: Cannot read property 'setState' of undefined
My github repo
https://github.com/dolphine4u/demo-app
APP component
import React from 'react';
import {FetchData} from "../service/flickerApi.service";
import Header from "./header/header.component";
import Navigation from "./navigation/navigation.component";
import ProductList from "./products/products.component";
import Footer from "./footer/footer.component";
class App extends React.Component {
constructor() {
super()
this.state = {
feeds: [],
favorites:[]
};
this.addToFavorites = this.addToFavorites.bind(this);
}
handleChange( value ) {
this.setState( { feeds: value })
}
addToFavorites(id) {
const {feeds ,favorites} = this.state;
const findId = feeds.filter(item => {
return item.id === id;
})
favorites.push(findId)
console.log(favorites)
// localStorage.setItem('favorite', JSON.stringify(this.state.favorites));
this.setState({
feeds: favorites
});
}
/* componentWillMount(){
let LoadFeeds = localStorage.getItem('FlickerFeeds');
LoadFeeds && this.setState({
feeds: JSON.parse(LoadFeeds)
})
}*/
componentDidMount() {
FetchData.call(this);
}
/* componentWillUpdate(nextprops, nextState){
localStorage.setItem('FlickerFeeds', JSON.stringify(nextState.feeds))
}
*/
render() {
const {feeds} = this.state;
const productList = feeds.map((item,index) => {
return <ProductList
key={index}
title={item.title}
image={item.src}
id={item.id}
author={item.author}
date={item.created}
update={this.addToFavorites}
/>
})
return ([
<Header key="header"/>,
<Navigation key="navigation" />,
<section key="productList">
<div className="container">
<div className="row row-eq-height">
{productList}
</div>
</div>
</section>,
<Footer key="footer"/>
]);
}
}
export default App;
Navigation component
import React from 'react';
import Link from "./link.component";
import './navigation.css';
class Navigation extends React.Component {
constructor(props) {
super(props)
this.state = {
tags: [
{tag:"kittens"},
{tag:"dogs"},
{tag:"lion"},
{tag:"tiger"},
{tag:"leapord"}]
};
}
render() {
const {tags} = this.state;
const tagList = tags.map(item => {
return <Link
key={item.tag}
tag={item.tag}
/>
})
return (
<nav className="nav">
<div className="container">
<ul className="nav-bar">
{tagList}
</ul>
</div>
</nav>
);
}
}
export default Navigation;
Link Component
import React from 'react';
import {FetchData} from "../../service/flickerApi.service";
class Link extends React.Component {
constructor(props) {
super(props)
this.onClick = this.onClick.bind(this);
}
onClick(e) {
FetchData(this.props.tag);
}
render() {
return (
<li><a href="#" onClick={this.onClick}>{this.props.tag}</a></li>
);
}
}
export default Link;
product component
import React from 'react';
import './product.css';
class ProductList extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick(e) {
this.props.update(this.props.id);
}
render() {
return (
<div className="product-column">
<div className="product-item">
<div className="product-content">
<div className="product-author">
<strong>Author: </strong>{this.props.author}
</div>
{/*<div className="product-image" style={{backgroundImage: "url(" + this.props.image + ")"}}/>*/}
</div>
<div className="product-content">
<div className="product-date">
Created Date: {this.props.date}
</div>
<h3 className="product-title">{this.props.title}</h3>
<button className="product-btn" onClick={this.onClick}>
Add to Favourites
</button>
</div>
</div>
{/*<div className="product-description" dangerouslySetInnerHTML={{__html: this.props.description}}>
</div>*/}
</div>
);
}
}
export default ProductList;
Api service
import $ from "jquery";
import {getLastPartOfUrl, formatDate, removeUrl, getString} from "../helpers/helper";
export function FetchData(tag) {
const URL = "https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?"
const SUFFIX_SMALL_240 = "_m";
const SUFFIX_SMALL_320 = "_n";
$.getJSON({
url : URL,
data: {
tags: tag
}
})
.then(response => {
let list= response.items.map(item => ({
title: removeUrl(item.title),
id: getLastPartOfUrl(item.link),
description: item.description,
link: item.link,
src: item.media.m.replace(SUFFIX_SMALL_240, SUFFIX_SMALL_320),
author: getString(item.author),
created: formatDate(item.published),
tags: item.tags,
fav: false
}));
this.setState({
feeds: list
})
}).catch(function(error){
console.log(error);
});
}
You're trying to call this.addToFavorites from a click handler that is not even bound to this. I think two changes are needed for this to work:
In App component, change the addFavorites function to an arrow function so it gets the context this:
addToFavorites = id => {
...
Same in ProductList component for the click handler:
onClick = () => {
this.props.update(this.props.id);
}
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 },
}
}