Linked Questions

Popular Questions

Component with form keeps refreshing page in ReactJS

Asked by At

I'm attempting at creating a simple todo app to try to cement some concepts. This app gets some previous todos from a .js file with json object. And every time they get clicked they are deleted from the current app.

Now I wanted to add the ability to add todos, first to the current instance of app itself and afterwards to the file to ensure continuity.

My problem arises adding to the app instance.

When using the component with a form, it all goes south.

I tried putting all the component parts in the App.js main file but still the same result, it refreshes after the alert(value) line.

I've also tried changing the order inside the addTodo function and the alert only works if it's the first line of the function, anywhere else the refresh happens before it. So I assumed it's something about using the state of the app component?


import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import todosData from "./todosData"
import TodoItem from "./TodoItem"
import TodoForm from './TodoForm'
class App extends Component {

    constructor() {
        this.state = {
            todos: todosData
    this.handleChange = this.handleChange.bind(this)

  handleChange(id) {
        const allTodos = this.state.todos
        const filtered = allTodos.filter(x => !== id)
        const filtered2 = filtered
        filtered2.push({id:4,text:"HAKUNA MATATA",completed:false   })
        //added testing so that whenever I delete a todo it adds one with "HAKUNA MATATA"

    addTodo(value) {
        const allTodos = this.state.todos
        const lastTodo = this.state.todos.slice(-1)[0]
        const newId = + 1
        const newTodo = {id: newId, text: value, completed:false}

  render() {
    const todoItems = item =>
        const text = ""
    return (
      <div className="todo-list">
                <TodoForm addTodo={this.addTodo}/>

export default App;


import React from 'react'

class TodoForm extends React.Component {
  constructor(props) {
    this.handleSubmit = this.handleSubmit.bind(this)

  handleSubmit(event) {

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          <input type="text" ref={(input) => this.input = input}/>


export default TodoForm

Can you guys help me with this? From what I understood preventDefault was supposed to prevent this?

Related Questions