0

This is my code for a modal form I'm using and I wanted to use my function to console.log, but I'm not sure how to change the state in this.set.state? Any help is appreciated since Im very new to react. The variable st is just the string it takes in each time

interface State {
  name: string;
  email: string;
  amt: string;
}

interface Props {
  isOpen: boolean;
  handleClose: () => void;
  handleSendRequest: (values: State) => void;
}

    export default class FormDialog extends React.Component<Props, State> {
      state = { name: "", email: "", amt: "" };

      onChange = ((st: string) => (event: any) => {
        const newObject: any = {};
        newObject[st] = event.target.value;
        this.setState({ State: newObject[st] }); //this part im struggling with
      }).bind(this);

      render() {
        const { isOpen, handleClose, handleSendRequest } = this.props;
        return (
          <Dialog
            open={isOpen}
            onClose={handleClose}
            aria-labelledby="form-dialog-title"
          >
            <DialogTitle id="form-dialog-title">Send Money Request</DialogTitle>
            <DialogContent>
              <TextField
                autoFocus
                margin="dense"
                id="standard-read-only-input"
                name="name"
                label="Contact Name"
                defaultValue="John"
                onChange={this.onChange("name")}
              />
0

2 Answers 2

1

CodeSandbox example


You can cast newObject as seen below. This answer was derived from this Stack Overflow answer.

onChange = (st: string) => (event: any) => {
  const newObject = { [st]: event.target.value } as Pick<State, keyof State>;
  this.setState(newObject);
};



EDIT:

In response to: [H]ow it come it doesn't work for default values in the text field? If i take the default tag off and enter a new value it works tho

This is because defaultValue for your input is hard coded. Your component doesn't know about the value you defined in your input. You would have to move the default value into your state and provide the value to the <TextField /> component.


export default class FormDialog extends React.Component<Props, State> {
  state = {
    name: "John", // Define the default value here
    email: "",
    amt: "",
  };

  onChange = (st: string) => (event: any) => {
    const newObject = { [st]: event.target.value } as Pick<State, keyof State>;
    this.setState(newObject);
  };

  render() {
    return (
      <TextField
        defaultValue={this.state.name} // Pass the default value as a prop here
        onChange={this.onChange("name")}
      />
    );
  }
}

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! Quick, question though, how it come it doesn't work for default values in the text field? If i take the default tag off and enter a new value it works tho
I'm sorry, I don't understand what you're asking. Could you clarify what do you mean by "default values in the text field"? By default value, are you referring to "name" in this.onChange("name")?
In the code I posted, I have the text field: <DialogContent> <TextField autoFocus margin="dense" id="standard-read-only-input" name="name" label="Contact Name" defaultValue="John" onChange={this.onChange("name")} /> with a default value John. If I press submit right now, I dont see John in the console. However if I delete John as a default and type it by hand and then press submit, I can see it in the console
I updated my answer and CodeSandbox to address your question.
Thank you for your answer, helped me a lot!
1

Here is a simple example in javascript, which will log the state after it has been changed.

class Hello extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: ""
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {

    this.setState({
      name: event.target.value
    }, () => console.log(this.state));
  }
  render() {
    return <div > < input type = "text"
    id = "name"
    onChange = {
      this.handleChange
    }
    /></div > ;
  }
}

ReactDOM.render( <
  Hello / > ,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.