M
M
MrYogurt2020-10-03 15:01:46
React
MrYogurt, 2020-10-03 15:01:46

Where does the is not a function error come from?

There is a code:

class AddNewElement extends React.Component {

    constructor (props) {
        super(props);
        this.state = {
            input: ''
        };
        ....
        this.handleAddElement = this.handleAddElement.bind(this);
    }

    ....

    handleAddElement = (e) => {
        e.preventDefault();
        this.props.AddBrand(this.state.input);
    }

    render () {
        return (
          ....
                    <button onClick={this.handleAddElement}>Добавить</button>
                    ....
        )
    }
}

class Show extends React.Component {

    constructor (props) {
        super(props);
        this.state = {
            names: ["name1", "name2", "name3",]
        };
    }

    AddBrand(name) {
        this.setState((prevState) => ({ names: [...prevState.names, name] }));
    }

    render() {
        return (
            <div>
                <ElementList names={this.state.names} AddBrand={this.AddBrand.bind(this)}/>
            </div>
        );
    }
}

function ElementList({names, AddBrand}) {
    return names.map((name) => (
        <Element key={name} brand={name} AddBrand={AddBrand}/>
    ));
}


By clicking on "handleAddElement" the state of the input should fall into the "names" array, in the "Show" component state and add a new element, but I get the error "TypeError: this.props.AddBrand is not a function". With binds everything seems to be in order, tell me what the problem is.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-10-03
@MrYogurt

I don't see where you are passing AddBrand to AddNewElement, use propTypes to control props. Never bind in props, change the method to an arrow function. Well, if the code is new, read the original documentation and make functional components.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question