user3808307
user3808307

Reputation: 1471

Why is my react form not working on codesandbox

I created a simple form here https://codesandbox.io/s/xenodochial-frog-7squw

It says You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue.

But there is an onChange handler being passed, so I don't understand. In addition the page reloads when I hit submit, even though preventDefault() is called

Thank you

Upvotes: 0

Views: 1219

Answers (3)

Taghi Khavari
Taghi Khavari

Reputation: 6582

here is the correct Code for you:

import React from "react";
import "./styles/styles.css";

import Form from "./components/Form";
import Table from "./components/Table";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { str: "", desc: false };
    console.log(4444);
    this.handleChange = this.handleChange.bind(this); //<-- this binding
  }

  handleSubmit = event => {
    event.preventDefault();
    console.log("submitted");
  };

  handleChange = event => {
    this.setState({ str: event.target.value });
  };

  render() {
    const { str } = this.state; // <-- FIXED THIS
    return (
      <div className="App">
        <Form str={str} onChange={this.handleChange} onSubmit={this.handleSubmit} />
        <Table />
      </div>
    );
  }
}

export default App;

Upvotes: 1

Simon
Simon

Reputation: 881

On line 25 you do:

const { str, handleChange, handleSubmit } = this.state;

Because of this, handleChange will be bound to this.state.handleChange which will be undefined as you have no property handleChange in your state.

You also forgot to pass the prop name to your Table-component.

I forked your code and updated it here: https://codesandbox.io/s/modest-meninsky-y1sgh

Upvotes: 1

Clarity
Clarity

Reputation: 10873

The issue is this line:

const { str, handleChange, handleSubmit } = this.state;

handleChange and handleSubmit are not part of the state, but are instance methods, so you can pass them like so:

    return (
      <div className="App">
        <Form str={str} onChange={this.handleChange} onSubmit={this.handleSubmit} />
        <Table />
      </div>
    );

Upvotes: 3

Related Questions