Reputation: 1005
I'm currently building a ToDo-List App in react and I'm getting the following error message:
TypeError: props.onSubmit is not a function:
16 | const handleSubmit = e => {
17 | e.preventDefault();
18 | `enter code here`
> 19 | props.onSubmit({
| ^ 20 | id: Math.floor(Math.random() * 1000),
21 | text: input
22 | });
This is the function that I wrote inside of the following file TodoForm.js:
import React, { useState, useEffect, useRef } from 'react';
function TodoForm(props) {
const [input, setInput] = useState(props.edit ? props.edit.value : '');
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
});
const handleChange = e => {
setInput(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
props.onSubmit({
id: Math.floor(Math.random() * 1000),
text: input
});
setInput('');
};
return (
<form onSubmit={handleSubmit} className='todo-form'>
{props.edit ? (
<>
<input
placeholder='Update your item'
value={input}
onChange={handleChange}
name='text'
ref={inputRef}
className='todo-input edit'
/>
<button onClick={handleSubmit} className='todo-button edit'>
Update
</button>
</>
) : (
<>
<input
placeholder='Add a todo'
value={input}
onChange={handleChange}
name='text'
className='todo-input'
ref={inputRef}
/>
<button onClick={handleSubmit} className='todo-button'>
Add todo
</button>
</>
)}
</form>
);
}
export default TodoForm;
Could someone please help me to understand what I'm doing wrong?
Upvotes: 1
Views: 4605
Reputation: 42170
@BrianThompson is right that the problem is way higher up in the chain. I looked at your repo and it's actually in App.js
.
You have a component TodoList
which calls TodoForm
with the onSubmit
function that it created. But in your App.js
you have accidentally used TodoForm
instead of TodoList
! You cannot use TodoForm
directly without supplying the necessary props, so you get an error.
function App() {
return (
<div className="todo-app">
<TodoForm />
<h1>To-Do App</h1>
</div>
);
}
Upvotes: 1
Reputation: 2923
In file https://github.com/hvaandres/TodoList_React/blob/main/todo_list_v2/src/App.js you call TodoForm
without supplying the onSubmit
function as a prop:
function App() {
return (
<div className="todo-app">
<TodoForm />
<h1>To-Do App</h1>
</div>
);
}
You need to create onSubmit function and pass it to to TodoForm like that:
const onSubmit = () => {
// implement what you are trying to do in this function
}
function App() {
return (
<div className="todo-app">
<TodoForm onSubmit={onSubmit}/>
<h1>To-Do App</h1>
</div>
);
}
Upvotes: 2