user3137766
user3137766

Reputation:

React undefined state

I just begin with react, i want to display cards from state :

import React, {Component} from 'react';
import personnages from './personnages';
import ChampRecherche from '../components/champrecherche';

class Cards extends Component {
    constructor (props) {
        super(props);
        this.state = {
            dataFromChild:null
        }
    }
    getVal = (dataFromChild) => {
        this.setState({ dataFromChild : dataFromChild })
    }
    listItems = personnages.map((perso) => {
        
        return <li style={{ display: perso.title.indexOf(this.state.dataFromChild) !== -1 ? 'block' : 'none' }} key={perso.id}>{perso.title}</li>  
    });
    render() {
        return(
            <div>
                <ChampRecherche callbackFromParent={this.getVal} />
                <ul>{this.listItems}</ul>
            </div>
        )  
    }
}

export default Cards;

I want to display block or none cards dynamically from a state, with code above i get an error :

TypeError: Cannot read property 'dataFromChild' of undefined

Could someone explains me a bit please?

Thank you.

Upvotes: 0

Views: 54

Answers (2)

Daniel Adepoju
Daniel Adepoju

Reputation: 821

listItems does not have access to this.state since it's not binded to the class object. That's why you're having that error. I'll suggest you make listItems a class function that returns what you need to map. something like listItems = () => personAges.map... Hope that solves your issue. Or you could bind as suggested by other answers.

Upvotes: 2

Yossi
Yossi

Reputation: 6027

You need to bind. In the constructor:

 this.listItems = this.listItems.bind(this)

Or when you call it:

this.listItems.bind(this)

In addition, you need to check the value as the other answer explains.

Upvotes: 0

Related Questions