i have an error in my react code, my result component is not changed after change array data, in console i just see new arrays after change input, new builded data is work, but component result isnot changed.
App.jsx
import React, { Component } from 'react'
import './App.css';
import fetch from 'isomorphic-fetch'
import Header from './Header'
import Content from './Content'
import Footer from './Footer'
class App extends Component {
constructor(props) {
super(props)
this.state = {
stripdata: null,
query: ""
}
this.query = this.query.bind(this)
}
componentWillMount() {
fetch(`http://localhost:3000/data/info.json`)
.then(results => results.json())
.then(data => {
this.setState({
stripdata: data
})
})
.catch(err => {
console.log("Didn't connect to API", err)
})
}
query(e) {
e = e.trim().toLowerCase();
this.setState({
query: e
})
}
show(data, query) {
return (query.length > 0) ?
data.filter(item => { return item.fakename.stripclub.toLowerCase().match( query ) }) :
data
}
render() {
console.log(this.show(this.state.stripdata, this.state.query))
return (
<div className="App">
<Header onQuery={this.query}/>
{
(this.state.stripdata === null) ?
<div className="loading">Loading data...</div> :
<Content onResult={ this.show(this.state.stripdata, this.state.query) }/>
}
<Footer />
</div>
);
}
}
export default App;
Content.jsx
import React, { Component } from 'react'
import Result from './Result'
class Content extends Component {
constructor(props) {
super(props);
this.state = {
stripdata: this.props.onResult
};
}
componentWillMount() {
}
render() {
return (
<div className="Content">
<Result stripdata={ this.state.stripdata }/>
</div>
);
}
}
export default Content;
Finder.jsx
import React, { Component } from 'react'
class Finder extends Component {
constructor(props) {
super(props)
this.state = {}
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
this.props.find(e.target.value)
}
render() {
return (
<div className="Finder">
<form id="search" onSubmit="">
<span>i want</span>
<input type="text"
placeholder="type who you want"
onChange={ this.handleChange }
/>
</form>
</div>
);
}
}
export default Finder;
Header.jsx
import React, { Component } from 'react'
import Finder from './Finder'
class Header extends Component {
constructor(props) {
super(props);
this.state = {
};
this.find = this.find.bind(this);
}
find(e) {
this.props.onQuery(e)
}
render() {
return (
<div className="Header">
<div className="inner">
<h2>Find with which girl you want to spend your time !!!</h2>
<Finder find={ this.find }/>
</div>
</div>
);
}
}
export default Header;
Result.jsx
import React, { Component } from 'react'
import PersonCard from './PersonCard'
class Result extends Component {
constructor(props) {
super(props);
this.state = {
stripdata: this.props.stripdata
};
}
componentWillMount() {
}
render() {
return (
<div className="result">
{
this.state.stripdata.map((item, i) => {
return <PersonCard key={i} data={item}/>
})
}
</div>
);
}
}
export default Result;
import React, { Component } from 'react'
import Facebook from 'react-icons/lib/fa/facebook'
import VK from 'react-icons/lib/fa/vk'
import Phone from 'react-icons/lib/fa/phone'
PersonCard.jsx
class PersonCard extends Component {
constructor(props) {
super(props);
this.state = {
info: this.props.data
};
}
render() {
var now = new Date().getFullYear();
return (
<div className="PersonCard">
<div className="layer one">
<div className="side left face-image">
<img src={(this.state.info.photo) ? this.state.info.photo : ""} alt="Person Pic" />
</div>
<div className="side right info">
<p><b>Fake Name:</b> { this.state.info.fakename.stripclub }</p>
<p><b>Real Name:</b> { (this.state.info.name) ? this.state.info.name : null }</p>
<p><b>Currently Workplace:</b> { (this.state.info.address.work ) ? this.state.info.address.work : null }</p>
<p><b>Age:</b> { (this.state.info.born) ? (now - this.state.info.born.slice(0, 4)) : null }</p>
<p><br /><a href={ (this.state.info.fakename.facebook) ? this.state.info.fakename.facebook.id : null } ><icon><Facebook /></icon> { (this.state.info.fakename.facebook) ? this.state.info.fakename.facebook.user : null }</a></p>
<p><br /><a href={ (this.state.info.fakename.vk) ? this.state.info.fakename.vk.id : null }><icon><VK /></icon> { (this.state.info.fakename.vk) ? this.state.info.fakename.vk.user : null }</a></p>
<p><br /><a href={ (this.state.info.phone) ? "tel:" + this.state.info.phone : null }><icon><Phone /></icon> { (this.state.info.phone) ? this.state.info.phone : null }</a></p>
</div>
</div>
<div className="layer two">
<div className="about">
<p>{ this.state.info.physical }</p>
<p>{ (this.state.info.work_days) ? 'All Week ' + this.state.info.work_days : null }</p>
</div>
</div>
</div>
);
}
}
export default PersonCard;
Please help me with with this issue.
Try to write the Content component like this:
class Content extends Component {
render() {
return (
<div className="Content">
<Result stripdata={ this.props.onResult }/>
</div>
);
}
}
And the Result component like this also:
class Result extends Component {
render() {
return (
<div className="result">
{
this.props.stripdata.map((item, i) => {
return <PersonCard key={i} data={item}/>
})
}
</div>
);
}
}
And in the PersonCard replace every reference of this.state to this.props and remove the assignment in the constructor.
I am guessing the problem is with the assignments of props into state like in the Content component:
constructor(props) {
super(props);
this.state = {
stripdata: this.props.onResult
};
}
the constructor is probably not getting called after the input values changes.
The assumption that the constructor is getting called every time the component is rendered confuses a lot of beginner react devs...
Anyway you dont need to use state in these presentational components (https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0)
just use props.
Related
Edit: I have included the full code for better clarity
I am not sure if this is possible. I am trying to pass an onClick event via props but the click event does not work.
The parent component looks like this:
import React from 'react'
import { getProductsById } from '../api/get'
import Product from './Product'
import { instanceOf } from 'prop-types'
import { withCookies, Cookies } from 'react-cookie'
class Cart extends React.Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
}
constructor(props) {
super(props)
const { cookies } = props;
this.state = {
prods: cookies.get('uircartprods') || '',
collapsed: true,
total: 0,
}
this.expand = this.expand.bind(this)
this.p = [];
}
componentDidMount() {
this.getCartProducts()
}
handleClick = (o) => {
this.p.push(o.id)
const { cookies } = this.props
cookies.set('uircartprods', this.p.toString(), { path: '/' , sameSite: true})
this.setState({prods: this.p })
console.log('click')
}
getCartProducts = async () => {
let products = []
if (this.state.prods !== '') {
const ts = this.state.prods.split(',')
for (var x = 0; x < ts.length; x++) {
var p = await getProductsById(ts[x])
var importedProducts = JSON.parse(p)
importedProducts.map(product => {
const prod = <Product key={product.id} product={product} handler={() => this.handleClick(product)} />
products.push(prod)
})
}
this.setState({products: products})
}
}
expand(event) {
this.setState({collapsed: !this.state.collapsed})
}
handleCheckout() {
console.log('checkout clicked')
}
render() {
return (
<div className={this.state.collapsed ? 'collapsed' : ''}>
<h6>Your cart</h6>
<p className={this.state.prods.length ? 'hidden' : ''}>Your cart is empty</p>
{this.state.products}
<h6>Total: {this.props.total}</h6>
<button onClick={this.handleCheckout} className={this.state.prods.length ? '' : 'hidden' }>Checkout</button>
<img src="./images/paypal.png" className="paypal" alt="Paypal" />
<a className="minify" onClick={this.expand} alt="My cart"></a>
<span className={this.state.prods.length ? 'pulse' : 'hidden'}>{this.state.prods.length}</span>
</div>
)
}
}
export default withCookies(Cart)
The Product component:
import React from 'react';
class Product extends React.Component {
constructor(props) {
super(props);
this.state = {
showDetails: false,
showModal: false,
cart: []
}
this.imgPath = './images/catalog/'
}
render() {
return (
<div className="Product">
<section>
<img src={this.imgPath + this.props.product.image} />
</section>
<section>
<div>
<h2>{this.props.product.title}</h2>
<h3>{this.props.product.artist}</h3>
<p>Product: {this.props.product.product_type}</p>
<h4>${this.props.product.price}</h4>
<button className="button"
id={this.props.product.id} onClick={this.props.handler}>Add to cart</button>
</div>
</section>
</div>
)
}
}
export default Product
If I log this.props.handler I get undefined. Everything works apart from the click handler, I was wondering if it might have something to with the async function. I am very new to React, there are still some concepts I'm not sure about, so any help is appreciated.
Okay, I see a few issues here.
First, there is no need to call this.handleClick = this.handleClick.bind(this) in the constructor, because you are using an arrow function. Arrow functions do not have a this context, and instead, accessing this inside your function will use the parent this found in the Class.
Secondly, it is wrong to store components in state. Instead, map your importedProducts inside the render function.
Thirdly, the issue with your handler is that this.props.handler doesn't actually call handleClick. You will notice in the definition handler={(product) => this.handleClick} it is returning the function to the caller, but not actually calling the function.
Try this instead.
class Product extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<button className="button" id={this.props.product.id} onClick={this.props.handler}>
Add to cart
</button>
</div>
);
}
}
export default Product;
import Product from './Product'
class Cart extends React.Component {
constructor(props) {
super(props);
}
handleClick = (o) => {
console.log('click');
};
render() {
return (
<div>
{importedProducts.map((product) => {
return <Product key={product.id} product={product} handler={() => this.handleClick(product)} />;
})}
</div>
);
}
}
export default Cart;
I'm currently building a ReactJS Weather app where I have a drop-down list with different cities and a container with the information about weather on the selected city. When i fetch the weather data from an API i have a default city and I want to refetch the data when user selects another city in the dropdown list.
I will provide you with the code.
App.jsx class (the main class)
import React, { Component } from "react";
import "./sass/app.scss";
import axios from "axios";
import { Dropdown } from "semantic-ui-react";
import NavigationBar from "./components/NavigationBar";
import WeatherComponent from "./components/WeatherComponent";
import { locationOptions } from "./locations.js";
const WEATHER_KEY = "5f0f0f2a61c0f3f650984fb442f03d86";
class App extends Component {
constructor(props) {
super(props);
this.state = {
cityName: "Pristina",
isLoading: true,
isSelectedLocationOpen: false
};
}
componentDidMount() {
const { cityName } = this.state;
const { eventEmitter } = this.props;
const URL = `http://api.weatherstack.com/current?access_key=${WEATHER_KEY}&query=${cityName}`;
axios
.get(URL)
.then(res => {
return res.data;
})
.then(data => {
this.setState({
isLoading: false,
name: data.location.name,
country: data.location.country,
temperature: data.current.temperature,
weather_descriptions: data.current.weather_descriptions[0],
weather_icons: data.current.weather_icons[0],
observation_time: data.current.observation_time
});
})
.catch(err => {
console.error("Cannot fetch weatcher from API", err);
});
eventEmitter.on("updateLocation", data => {
this.setState({ cityName: data });
});
}
handleChange() {
const { eventEmitter } = this.props;
const { cityName } = this.state;
eventEmitter.emit("updateLocation", cityName);
}
render() {
const {
isLoading,
name,
temperature,
weather_descriptions,
weather_icons,
observation_time,
country
} = this.state;
return (
<div className="main-container">
<div className="first-container">
<div className="wrapper">
{isLoading && <h3>Loading ...</h3>}
<NavigationBar />
{!isLoading && (
<WeatherComponent
className="weather-container"
name={name}
temperature={temperature}
weather_descriptions={weather_descriptions}
weather_icons={weather_icons}
observation_time={observation_time}
country={country}
/>
)}
<Dropdown
placeholder="Select location"
search
selection
defaultValue={this.state.cityName}
options={locationOptions.map(item => {
return {
key: item.key,
value: item.value,
text: item.text
};
})}
onChange={this.handleChange}
value={locationOptions.value}
/>
</div>
</div>
</div>
);
}
}
export default App;
store.js class
import React from "react";
import { EventEmitter } from "events";
export default class Store extends React.Component {
constructor(props) {
super(props);
this.eventEmitter = new EventEmitter();
// Main App State
this.state = {
appName: "Weather App"
};
}
render() {
return React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
...this.state,
eventEmitter: this.eventEmitter
});
});
}
}
WeatherComponent.js
import React from "react";
import "../sass/weather.scss";
import sunnyIcon from "../assets/sunnyicon.png";
import sun from "../assets/sunicon.png";
export default class WeatherComponent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
// weather_descriptions i have to find a better icon for current weather
render() {
const {
temperature,
weather_descriptions,
observation_time,
name,
country
} = this.props;
return (
<div className="weather-container">
<div className="location-container">
<img src={sunnyIcon} className="logo2" alt="" />
<h1 className="total-weather-report">Today's weather report</h1>
<h1 className="location">{`${name}, ${country}`}</h1>
</div>
<div className="degree-container">
<img src={sunnyIcon} className="weather-logo2" alt="" />
<h2 className="degree-value">{`${temperature}°C`}</h2>
</div>
<div className="info-container">
<h2 className="local-weather-report">Local Weather Report</h2>
<div className="hr"></div>
<img src={sun} className="sun-icon" alt="" />
<h2 className="day">Sunday</h2>
<h2 className="weather-type">{weather_descriptions}</h2>
<h2 className="last-observation">Last observed on:</h2>
<h2 className="observation-time">{observation_time}</h2>
</div>
<div className="weekly-weather"></div>
</div>
);
}
}
When I run the app everything works but when I try to change the city from the dropdown, it crashes and this error pops-up.
The error
EventEmitter is part of the NodeJS API, is not available for browsers.
EDIT:
In App.jsx you have a function called "handleChange", that function should do the same thing you are doing on "componenDidMount" but using the actual value of the Dropdown, you don't need to manually create events.
Hope it helps
I'm trying to get a feel for reactjs, new to front end development. Google Books API is simple so I decided to use it to build a react page that lists 10 books given the user input.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const GOOGLE_BOOKS_API = 'https://www.googleapis.com/books/v1/volumes?q=';
const GOOGLE_BOOKS_API_LIMIT = 'maxResults=10';
class BookItem extends React.Component {
render() {
return (
<div>
<img alt="Book" src={this.props.data.volumeInfo.imageLinks.thumbnail} />
<span>{this.props.data.volumeInfo.imageLinks.thumbnail}</span>
</div>
);
}
}
class BookResults extends React.Component {
render() {
const isBookResultsEmpty = !(this.props.books && this.props.books.length > 1);
const bookItems = isBookResultsEmpty ? [] : this.props.books.map((book,index) =>
<BookItem key={index} data={book} />
);
return (
<div className='book-results'>
{isBookResultsEmpty ? (
<h1>No Results</h1>
) : (
<div> {bookItems} </div>
)}
</div>
);
}
}
class BookSearch extends React.Component {
constructor(props) {
super(props);
this.state = {
bookQuery: '',
books: []
};
this.handleInputChange = this.handleInputChange.bind(this);
this.getBooks = this.getBooks.bind(this)
}
getBooks() {
let queryString = '';
if (this.state.bookQuery && this.state.bookQuery.length > 1) {
queryString = this.state.bookQuery.replace(/\s/g, '+');
fetch(`${GOOGLE_BOOKS_API}${queryString}&${GOOGLE_BOOKS_API_LIMIT}`)
.then(results => {
return results.json();
})
.then(json => {
this.setState({
books: json.items
});
})
.catch(e => console.log('error', e));
}
}
handleInputChange(event) {
this.setState({
bookQuery: this.search.value
},
this.getBooks());
}
render() {
return (
<div className="book-search">
<form>
<input
placeholder="Search for Books"
ref={input => this.search = input}
onChange={this.handleInputChange}
/>
</form>
<BookResults books={this.state.books} />
</div>
);
}
}
ReactDOM.render(<BookSearch />, document.getElementById('root'));
I get an error when typing the input:
TypeError: Cannot read property 'thumbnail' of undefined
I added a check for the data in the BookResults component but the error still occurs. I assume it has to do with the state or props value changing while rendering, but I don't know enough about React to be sure
Some books don't have imageLinks, so you need to make sure it is not undefined before you use it.
Example
class BookItem extends React.Component {
render() {
const { imageLinks } = this.props.data.volumeInfo;
if (!imageLinks) {
return null;
}
return (
<div>
<img alt="Book" src={imageLinks.thumbnail} />
<span>{imageLinks.thumbnail}</span>
</div>
);
}
}
I'm trying to render buttons to a page which when clicked render the hard-coded weather data to the page depending on the day that was clicked. The click function works fine and the buttons are rendered just as I expect them to, but when a button is clicked the Day component doesn't render.
I don't understand what I'm doing wrong since my code reaches the console.log in the click handler function. Then the handler function should render the component but for some reason it does not.
Here is my code:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import myData from "./weather.json";
class Day extends React.Component {
constructor(props) {
super(props);
this.state = {
description: null
};
}
render() {
console.log("at last"); //this isn't reached
return (
<div className="dayWeather">
<div className="dayWeather">Humidity {this.props.humidity}</div>
<div className="dayWeather">Temperature {this.props.temperature}</div>
</div>
);
}
}
class DayRow extends React.Component {
constructor(props) {
super(props);
this.state = {
days: Array(7).fill(null)
};
this.handler = this.handler.bind(this);
this.renderDay = this.renderDay.bind(this);
}
handler(day) {
let daysWeather = myData[day];
console.log("now we've reached this far"); //this console log is reached when a button is clicked.
return (
<Day
humidity={daysWeather.humidity}
temperature={daysWeather.temperature}
/>
);
}
renderDay(day) {
return (
<div>
<button
className="day"
onClick={() => {
this.handler(day);
}}
>
{day}
</button>
</div>
);
}
render() {
return (
<div>
<div className="day-row">
{this.renderDay("Monday")}
{this.renderDay("Tuesday")}
{this.renderDay("Wednesday")}
{this.renderDay("Thursday")}
{this.renderDay("Friday")}
{this.renderDay("Saturday")}
{this.renderDay("Sunday")}
</div>
</div>
);
}
}
class Weather extends React.Component {
render() {
return (
<div className="weather">
<div className="weather-panel">
<DayRow />
</div>
<div className="day" />
</div>
);
}
}
// ========================================
ReactDOM.render(<Weather />, document.getElementById("root"));
Don't return UI elements in click handler as it won't render. Just set a flag inside handler and use it to display the Day component inside your render function.
class DayRow extends React.Component {
constructor(props) {
super(props);
this.state = {
days: Array(7).fill(null),
showDay: false
};
this.handler = this.handler.bind(this);
this.renderDay = this.renderDay.bind(this);
}
handler() {
this.setState({
showDay: true,
});
}
renderDayComponent(day) {
let daysWeather = myData[day];
console.log("now we've reached this far"); //this console log is reached when a button is clicked.
return (
<Day
humidity={daysWeather.humidity}
temperature={daysWeather.temperature}
/>
);
}
renderDay(day) {
return (
<div>
<button
className="day"
onClick={() => {
this.handler();
}}
>
{day}
</button>
{this.state.showDay && this.renderDayComponent(day)}
</div>
);
}
render() {
return (
<div>
<div className="day-row">
{this.renderDay("Monday")}
{this.renderDay("Tuesday")}
{this.renderDay("Wednesday")}
{this.renderDay("Thursday")}
{this.renderDay("Friday")}
{this.renderDay("Saturday")}
{this.renderDay("Sunday")}
</div>
</div>
);
}
}
My guess is that you are trying to render the day in the Weather compoment? To do this, you must keep some sort of state so that React knows what to render. Whenever you change the state, React will call render to re-render your compoment.
Therefore, since the state of wether or not a day is to be shown is local to the Weather component, you need to store the state there:
class Weather extends React.Component {
constructor(props) {
super(props)
this.state = { activeDay: undefined }
}
render() {
// Store the current dayData in a variable if an activeDay is chosen, it will be falsy if no day has been chosen.
const dayData = this.state.activeDay && myData[this.state.activeDay]
return (
<div className="weather">
<div className="weather-panel">
// DayRow will inform Weather when a day has been selected, i.e., clicked
<DayRow onSelected={day => this.setState({ activeDay: day })} />
</div>
<div className="day">
// This is where you are rendering the day, only if a day
// is active. I.e., dayData is truthy
{ dayData && <Day humitidy={dayData.humitidy} temperature={dayData.temperature} /> }
</div>
</div>
);
}
}
Your DayRow would simple communicate with Weather by saying which day is selected.
class DayRow extends React.Component {
constructor(props) {
super(props);
this.renderDay = this.renderDay.bind(this)
}
renderDay(day) {
return (
<div>
<button
className="day"
onClick={() => {
this.props.onSelected(day);
}}
>
{day}
</button>
</div>
);
}
render() {
return (
<div>
<div className="day-row">
{this.renderDay("Monday")}
{this.renderDay("Tuesday")}
{this.renderDay("Wednesday")}
{this.renderDay("Thursday")}
{this.renderDay("Friday")}
{this.renderDay("Saturday")}
{this.renderDay("Sunday")}
</div>
</div>
);
}
}
Returning JSX from your event handler will not render it. You have to do all rendering in your component's render method.
You could instead have an additional object in your state that keep track of if the day has been clicked or not, and use that state in your rendering.
class DayRow extends React.Component {
constructor(props) {
super(props);
this.state = {
days: Array(7).fill(null),
showDays: {}
};
this.handler = this.handler.bind(this);
this.renderDay = this.renderDay.bind(this);
}
handler(day) {
this.setState(previousState => {
const showDays = { ...previousState.showDays };
showDays[day] = !showDays[day];
return { showDays };
});
}
renderDay(day) {
let daysWeather = myData[day];
return (
<div>
<button
className="day"
onClick={() => {
this.handler(day);
}}
>
{day}
</button>
{this.state.showDays[day] && (
<Day
humidity={daysWeather.humidity}
temperature={daysWeather.temperature}
/>
)}
</div>
);
}
// ...
}
The returned component from handler function is being passed to onClick event. Its not getting into the DOM tree.
You can change the code as shown below.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import myData from './weather.json';
const myData =
class Day extends React.Component {
constructor(props) {
super(props);
this.state = {
description: null
};
}
render() {
console.log('at last'); //this isn't reached
return (
<div className="dayWeather">
<div className="dayWeather">Humidity {this.props.humidity}</div>
<div className="dayWeather">Temperature {this.props.temperature}</div>
</div>
);
}
}
class DayRow extends React.Component {
constructor(props) {
super(props);
this.state = {
days: Array(7).fill(null)
};
this.handler = this.handler.bind(this);
this.renderDay = this.renderDay.bind(this);
}
handler(day) {
let daysWeather = myData[day];
console.log('now we\'ve reached this far'); //this console log is reached when a button is clicked.
this.props.handler(daysWeather);
}
renderDay(day) {
return (
<div>
<button
className="day"
onClick={() => {
this.handler(day);
}}
>
{day}
</button>
</div>
);
}
render() {
return (
<div>
<div className="day-row">
{this.renderDay('Monday')}
{this.renderDay('Tuesday')}
{this.renderDay('Wednesday')}
{this.renderDay('Thursday')}
{this.renderDay('Friday')}
{this.renderDay('Saturday')}
{this.renderDay('Sunday')}
</div>
</div>
);
}
}
class Weather extends React.Component {
constructor(props){
super(props);
this.state = {
selectedDay: {}
};
this.handler = this.handler.bind(this);
}
handler(day){
this.setState({
selectedDay: day
});
}
render() {
let day = null;
if(Object.keys(this.state.selectedDay) > 0){
day = <Day
humidity={selectedDay.humidity}
temperature={selectedDay.temperature}
/>;
}
return (
<div className="weather">
<div className="weather-panel">
<DayRow onDayChange={this.handler}/>
</div>
<div className="day">
{day}
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(<Weather />, document.getElementById('root'));
I'm trying to call a simple method from the grandparent component in my child component but from some reason I can't , I tried every possible way but I think I'm missing something
here's the full code :
import React, { Component } from 'react';
import './App.css';
var todos = [
{
title: "Example2",
completed: true
}
]
const TodoItem = (props) => {
return (
<li
className={props.completed ? "completed" : "uncompleted"}
key={props.index} onClick={props.handleChangeStatus}
>
{props.title}
</li>
);
}
class TodoList extends Component {
constructor(props) {
super(props);
}
render () {
return (
<ul>
{this.props.todosItems.map((item , index) => (
<TodoItem key={index} {...item} {...this.props} handleChangeStatus={this.props.handleChangeStatus} />
))}
</ul>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
todos ,
text :""
}
this.handleTextChange = this.handleTextChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeStatus = this.handleChangeStatus(this);
}
handleTextChange(e) {
this.setState({
text: e.target.value
});
}
handleChangeStatus(){
console.log("hello");
}
handleSubmit(e) {
e.preventDefault();
const newItem = {
title : this.state.text ,
completed : false
}
this.setState((prevState) => ({
todos : prevState.todos.concat(newItem),
text : ""
}))
}
render() {
return (
<div className="App">
<h1>Todos </h1>
<div>
<form onSubmit={this.handleSubmit}>
< input type="text" onChange={this.handleTextChange} value={this.state.text}/>
</form>
</div>
<div>
<TodoList handleChangeStatus={this.handleChangeStatus} todosItems={this.state.todos} />
</div>
<button type="button">asdsadas</button>
</div>
);
}
}
export default App;
The method im trying to use is handleChangeStatus() from the App component in the TodoItem component
Thank you all for your help
This line is wrong:
this.handleChangeStatus = this.handleChangeStatus(this);
//Change to this and it works
this.handleChangeStatus = this.handleChangeStatus.bind(this);