I would like to set state of parent component from child component. I tried using props however its giving error Uncaught TypeError: this.props.setTopicClicked is not a function. And is there more efficient way for setting state of parent component instead of using props? I would like to set state of isTopicClicked: true
main-controller.jsx
import {React, ReactDOM} from '../../../build/react';
import SelectedTopicPage from '../selected-topic-page.jsx';
import TopicsList from '../topic-list.jsx';
import topicPageData from '../../content/json/topic-page-data.js';
export default class MainController extends React.Component {
state = {
isTopicClicked: false,
topicPageData
};
onClick(topicID) {
this.setState({
isTopicClicked: true,
topicsID: topicID
});
};
setTopicClicked(event){
this.setState({isTopicClicked: event});
};
render() {
return (
<div className="row">
{this.state.isTopicClicked
? <SelectedTopicPage topicsID={this.state.topicsID} key={this.state.topicsID} topicPageData={topicPageData}/>
: <TopicsList onClick={ this.onClick.bind(this) }/>}
</div>
);
}
};
selected-topic-page.jsx
import {React, ReactDOM} from '../../build/react';
import SelectedTopicPageMarkup from './selected-topic-page-markup.jsx';
import NextPrevBtn from './next-prev-btn.jsx';
export default class SelectedTopicPage extends React.Component {
state = {
topicPageNo: 0,
total_selected_topic_pages: 1
};
navigateBack(topicPageNo) {
if (this.state.topicPageNo > 0){
topicPageNo = this.state.topicPageNo - 1;
}
else {
topicPageNo = 0;
}
this.setState({topicPageNo : topicPageNo});
};
navigateNext(totalPagesInSelectedTopic) {
let topicPageNo;
if (totalPagesInSelectedTopic > this.state.topicPageNo + 1){
topicPageNo = this.state.topicPageNo + 1;
}
else if (totalPagesInSelectedTopic == this.state.topicPageNo + 1) {
this.props.setTopicClicked(true);
}
else {
topicPageNo = this.state.topicPageNo;
}
this.setState({topicPageNo : topicPageNo});
};
render() {
let topicsID = this.props.topicsID;
let topicPageNo = this.state.topicPageNo;
return (
<div>
{this.props.topicPageData.filter(function(topicPage) {
// if condition is true, item is not filtered out
return topicPage.topic_no === topicsID;
}).map(function (topicPage) {
let totalPagesInSelectedTopic = topicPage.topic_pages.length;
return (
<div>
<div>
<SelectedTopicPageMarkup headline={topicPage.topic_pages[0].headline} key={topicPage.topic_no}>
{topicPage.topic_pages[topicPageNo].description}
</SelectedTopicPageMarkup>
</div>
<div>
<NextPrevBtn moveNext={this.navigateNext.bind(this, totalPagesInSelectedTopic)} key={topicPage.topic_no} moveBack={this.navigateBack.bind(this, topicPageNo)}/>
</div>
</div>
);
}.bind(this))}
</div>
);
};
};
It seems you forgot to pass setTopicClicked to the child:
setTopicClicked={this.setTopicClicked.bind(this)}
Your <SelectedTopicPage /> does not contain setTopicClicked as props which results into the error
<SelectedTopicPage
topicsID={this.state.topicsID}
key={this.state.topicsID}
topicPageData={topicPageData}/>
You can try using a flux implementation to handle the state of your application and just pass props to the component. Otherwise, I think you're stuck in passing in setting the state using the component or its children.
Related
I am working on trying to get this counter for pintsLeft to work. This is my first project with React and I feel that I am either not passing the property of the array correctly or my function code is not set correctly.
^^^^KegDetail.js^^^^
import React from "react";
import PropTypes from "prop-types";
function KegDetail(props){
const { keg, onClickingDelete} = props
return (
<React.Fragment>
<hr/>
<h2>{keg.name} Made By {keg.brewery}</h2>
<p>abv {keg.abv}</p>
<h3>price {keg.price}</h3>
<p>{keg.pintsLeft} total pints left</p> {/* Make this a percentage */}
<hr/>
<button onClick={ props.onClickingEdit }>Update Keg</button>
<button onClick={()=> onClickingDelete(keg.id) }>Delete Keg</button>
<button onClick={()=> this.onSellingPint()}>Sell A Pint!</button>
</React.Fragment>
);
}
KegDetail.propTypes = {
keg: PropTypes.object,
onClickingDelete: PropTypes.func,
onClickingEdit:PropTypes.func,
onSellingPint:PropTypes.func
}
export default KegDetail;
That was my KegDetail.js
import React, {useState} from "react";
import NewKegForm from "./NewKegForm";
import DraftList from "./DraftList";
import KegDetail from "./KegDetail";
import EditKegForm from "./EditKegForm";
class DraftControl extends React.Component {
constructor(props){
super(props);
this.state = {
kegFormVisibleOnPage: false,
fullDraftList: [],
selectedKeg: null,
editing: false,
pints: 127,
};
this.handleClick = this.handleClick.bind(this);
this.handleSellingPint = this.handleSellingPint.bind(this);
}
handleClick = () => {
if (this.state.selectedKeg != null){
this.setState({
kegFormVisibleOnPage: false,
selectedKeg: null,
editing: false
});
} else {
this.setState(prevState => ({
kegFormVisibleOnPage: !prevState.kegFormVisibleOnPage,
}));
}
}
handleSellingPint = () => {
this.setState({
pints:this.state.pints-1
})
};
render() {
let currentlyVisibleState = null;
let buttonText = null;
if (this.state.editing){
currentlyVisibleState = <EditKegForm keg = {this.state.selectedKeg} onEditKeg = {this.handleEditingKegInDraftList} />
buttonText = "Return to the Draft List"
}
else if (this.state.selectedKeg != null){
currentlyVisibleState = <KegDetail keg = {this.state.selectedKeg} onClickingDelete = {this.handleDeletingKeg}
onClickingEdit = {this.handleEditClick} onSellingPint = {this.handleSellingPint}/>
buttonText = "Return to the Keg List"
My DraftControl.js code
I don't know what I am doing wrong. I cant get the keg.pintsLeft to pass a number when I console.log, So I may be targeting it incorrectly.
Thanks again!
Try it like this:
handleSellingPint = () => {
this.setState(prevState => {
return {
pints: prevState.pints-1
}
})
};
edit
Also, you invoke the onSellingPint() in a wrong way.
It's not a class component, so React doesn't know what does this refer to.
The function itself is passed in as a prop, so you should reference it like this: <button onClick={() => props.onSellingPint() />
handleSellingPint = (id) => {
const clonedArray = [...this.state.fullDraftList]
for (let i = 0; i < this.state.fullDraftList.length; i++){
if (clonedArray[i].id === id){
clonedArray[i].pintsLeft -= 1
}
}
this.setState({
fullDraftList: clone
});
}
Is what I came up with.
Since you are alteriting a state within an array, you need to clone the array and work on that array, not the "real" one.
Thanks for all your help!
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;
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
class MyStories extends React.Component {
addFavorite = (e) => {
this.setState({
bgcolor: "blue"
})
}
render () {
const { stories } = this.props;
const { storyBriefs } = this.props.stories.length > 0 ?
stories.map(t => (<div className="menu-inner-container"><p key={t.id}><Link to={`/stories/${t.id}`}>{t.attributes.title}</Link>
<div className="addFavoriteCss"
style={{backgroundColor: this.state.bgColor}}
onClick={this.addFavorite}> Favorite</div>
</p></div>))
//refactor - create a button that will allow for us to mark which our favorites are
return (
{ this.props.storyBriefs }
);
}
}
const mapStateToProps = state => {
return {
stories: state.myStories
}
}
export default connect(mapStateToProps)(MyStories)
getting this error
./src/components/MyStories.js
Line 26: Parsing error: Unexpected token, expected ":"
return (
^
{ this.props.storyBriefs }
);
}
I converted a functional component to a class component so that I could manipulate the state in order to change the color of the favorite button -- (I cannot use hooks or redux for the button function) Can anyone tell me what I am doing wrong?
You need to complete the ternary operator by adding :
const storyBriefs = this.props.stories.length > 0 ?
stories.map(t => (<div className="menu-inner-container"><p key={t.id}><Link to={`/stories/${t.id}`}>{t.attributes.title}</Link>
<div className="addFavoriteCss"
style={{backgroundColor: this.state.bgColor}}
onClick={this.addFavorite}> Favorite</div>
</p></div>))
: [] // you need something here after the ':', an empty array could be useful in this case
return storyBriefs
or you could shorten it to
return stories.map(t => (<div className="menu-inner-container"><p key={t.id}><Link to={`/stories/${t.id}`}>{t.attributes.title}</Link>
<div className="addFavoriteCss"
style={{backgroundColor: this.state.bgColor}}
onClick={this.addFavorite}> Favorite</div>
</p></div>))
As Jaromanda X said { this.props.storyBriefs } isn't valid. you need to provide the key value pair unless the variable doesn't have dot notation then you can define the object like that
This was the final code and it works,
import React from "react"
import { connect } from "react-redux"
import { Link } from "react-router-dom"
class MyStories extends React.Component {
constructor(props) {
super(props);
this.state = {
button: false
};
this.addFavorite = this.addFavorite.bind(this);
}
addFavorite = id => {
this.setState({
button: id
});
};
render() {
return this.props.stories.map(t => (
<div className="menu-inner-container">
<p key={t.id}>
<Link to={`/stories/${t.id}`}>{t.attributes.title}</Link>
<button
key={t.id}
className={this.state.button===t.id ? "buttonTrue" : "buttonFalse"}
onClick={() => this.addFavorite(t.id)}
>
Favorites
</button>
</p>
</div>
));
}
}
//refactor - create a button that will allow for us to mark which our favorites are
const mapStateToProps = state => {
return {
stories: state.myStories
};
};
export default connect(mapStateToProps)(MyStories);
I have two components, the parent "App" component and the Hero component which contains an image and left and right arrow.
I want to use the right arrow to move the imageIndex + 1 until it reaches the images.length, and I want to have the left arrow to have a condition that I can't subtract if imageIndex = 0.
So something like: ( This part of the code is not added in my code yet because I keep getting undefined)
if (this.props.imageIndex > 0) {
this.setState({
// decrease the imageIndex by 1
})
}
if (this.props.imageIndex < this.props.images.length - 1){
this.setState({
// increase the imageIndex by 1
})
}
will be the condition or something like it.
App.jS (Parent Component)
export default class App extends Component {
constructor() {
super();
this.state = {
language: "english",
render: 'overview',
imageIndex: 0,
}
}
render() {
// to make sure the state changes
console.log(this.state.language)
const {render} = this.state
return <Fragment>
<Hero imageIndex = {this.state.imageIndex} />
</Fragment>;
}
}
How would I add that in my Hero Component which contains this code:
Hero.js
class Hero extends Component {
constructor(props) {
super(props);
this._ToggleNext = this._ToggleNext.bind(this);
}
_ToggleNext(props) {
console.log(this.props.listing.images.length)
console.log(this.props.imageIndex)
}
_TogglePrev(props) {
console.log(this.props.listing.images.length)
console.log(this.props.imageIndex)
}
render() {
const { listing: { images = [], name, location = {} } = {} } = this.props;
return <div className="hero">
<img src={images[0]} alt="listing" />
<a onClick={this._TogglePrev}) className="hero__arrow hero__arrow--left">◀</a>
<a onClick={this._ToggleNext} className="hero__arrow hero__arrow--right">▶</a>
<div className="hero__info">
<p>{location.city}, {location.state}, {location.country}</p>
<h1>{name}</h1>
</div>
</div>;
}
}
const getHero = gql`
query getHero {
listing {
name
images
location {
address,
city,
state,
country
}
}
}
`;
export default function HeroHOC(props) {
return <Query
query={getHero}
>
{({ data }) => (
<Hero
{...props}
listing={data && data.listing || {}} // eslint-disable-line no-mixed-operators
/>
)}
</Query>;
}
One solution is to define the data and functionality in the parent component, in this case App, and pass those down as props to the child which will focus on the rendering.
(code not tested but should give you the basic idea)
class App extends Component {
state = {
imageIndex: 0,
listing: {
images: ['foo.jpg', 'bar.jpg'],
name: 'foo',
location: {...}
}
}
_ToggleNext = () => {
const { imageIndex, listing } = this.state;
if (imageIndex === listing.images.length - 1) {
this.setState({imageIndex: 0});
}
}
_TogglePrev = () => {
const { imageIndex, listing } = this.state;
if (imageIndex === 0) {
this.setState({imageIndex: listing.images.length - 1});
}
}
render() {
return (
<Fragment>
<Hero
listing={this.state.listing}
imageIndex={this.state.imageIndex}
toggleNext={this._ToggleNext}
togglePrev={this._TogglePrev}
/>
</Fragment>
);
}
}
Hero component:
const Hero = props => {
const { listing, imageIndex, togglePrev, toggleNext } = props;
return (
<div className="hero">
<img src={listing.images[imageIndex]}/>
<a onClick={togglePrev})>◀</a>
<a onClick={toggleNext}>▶</a>
<div className="hero__info">
...
</div>
</div>
);
};
I'm trying to set a class dynamically depending on the pros i send to the component. Somehow i get the error " Cannot read property 'state' of undefined".
I guess that this doesn't exist when i try to set the class of the state as a class? Do i have to rebind it before i use it in the render of the component?
var ReactDOM = require('react-dom');
var React = require('react');
class Button extends React.Component {
constructor(props) {
super(props);
console.log("BUTTON")
console.log(props);
this.state = {
class: "small-button"
};
props.options.map(function (option) {
if (option.Description > 10) {
this.setState({
class: "big-button"
});
}
});
console.log("STATE: " + this.state.class);
}
render() {
if (this.props.options) {
return (<div> {
this.props.options.map(function (option) {
return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
})
}
</div>
)
} else {
return <div>No options defined</div>
}
}
}
module.exports = Button;
It's a binding issue, you need to bind the function to use this keyword (correct context) inside that.
Use this:
render() {
if (this.props.options) {
return (<div> {
this.props.options.map((option) => {
return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
})
}
</div> )
} else {
return <div>No options defined</div>
}
}
Check this answer for more detail on arrow function and this keyword
One Suggestion: Don't put logic inside constructor and don't do setState also, use lifecycle method for that. Put that logic inside componentDidMount method or componentWillMount method.
Like this:
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
class: "small-button"
};
}
componentDidMount(){
this.props.options.forEach((option) => {
if (option.Description > 10) {
this.setState({
class: "big-button"
});
}
});
}
render() {
if (this.props.options) {
return (
<div>
{
this.props.options.map((option) => {
return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
})
}
</div>
)
}else{
return <div>No options defined</div>
}
}
}