0

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

user3808307
  • 2,270
  • 9
  • 45
  • 99

3 Answers3

3

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>
    );
Clarity
  • 10,730
  • 2
  • 25
  • 35
1

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

Simon
  • 871
  • 1
  • 11
  • 23
1

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;
Taghi Khavari
  • 6,272
  • 3
  • 15
  • 32