Raymond Hou
Raymond Hou

Reputation: 11

React this.props.function is not a function when passing in functions from parent component to child component

Im new to react and trying to follow this https://www.youtube.com/watch?v=I6IY2TqnPDA&t=538s tutorial video on Youtube to create a todo list app. Basically it passes addToDo function into the child component ToDoForm as props and then gets called in the handleSubmit of Child the component.

However im keep getting this TypeError: this.props.onSubmit is not a function. I have tried binding the function but the same error keeps popping up. When i console.log(this.props), it says undefined.

parent component:

    class App extends Component{
    
         state = {
          todos: []
      };
      
      addToDo = todo => {
        this.setState({
          todos: [todo, ...this.state.todos]
        });
      };
    
      render(){
        return (
          <div>
            <TodoForm onSubmit={this.addToDO} />
            {JSON.stringify(this.state.todos)}
          </div>
        )
      }
    }
    
    export default App;

child component:

import React, { Component } from 'react';
import shortid from 'shortid';

export default class TodoFrom extends Component {

        state = {
            text: ""
        };

    handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        });
    };

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.onSubmit({
            id: shortid.generate(),
            text: this.state.text,
            complete: false
        });
        this.setState({
            text: ""
        });
    };

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    name = "text"
                    value={this.state.text}
                    onChange={this.handleChange}
                    placeholder="todo..."
                />
                <button onClick={this.handleSubmit}>add todo</button>
            </form>
        )
    }
}

Someone please help

Upvotes: 1

Views: 1500

Answers (1)

Dillan Wilding
Dillan Wilding

Reputation: 1111

JavaScript is case sensitive so by passing in this.addToDO, you're referencing a non-existent function. Change

<TodoForm onSubmit={this.addToDO} />

to

<TodoForm onSubmit={this.addToDo} />

Upvotes: 1

Related Questions