1
votes

I am so new in React JS. I am not maintaining a code that is written by someone else. My question may be too basic, sorry for this.

There is a form in the page. Is page is re-rendered after clicking the Submit button ? In my onSubmit method, there is not a code piece that re-render the web page. For example, after submitting the form, I want to set a label "Register is successful or not". Also if there is a validation error in the form, I want to colorize the input fields.

Actually I do not know when react re-renders page and which part of the page it renders ? How can I force React to re-render somewhere in the page ?

This is my onSubmit method;

onSubmit(e) {
  e.preventDefault();

  this.setState({
    loading: true,
  });

  setTimeout(() => {
    this.setState({
      loading: false,
    });
  }, 1000);

  const data = this.constructFormData();

  fetch('/register', {
    method: 'POST',
    body: data,
  })
    .then(p => {
    if (p.status === 200) {
      return p.json();
    }

    throw '500';
  })
    .catch(err => {
    this.setState({
      error: true,
    });
  });
}

And below is my form definition ;

<form
    id="register-form"
    method="POST"
    onSubmit={this.onSubmit}
    autoComplete="off"
>
2
Can I recommend you to put this.setState({ loading: false, }); in the promise .then(p => { if (p.status === 200) { return p.json(); } throw '500'; }) That will stop the loading as soon as you get the response which is much better than fixed 1 second with setTimeout. - Mirakurun

2 Answers

3
votes

whenever you call setState(), form re-renders. You can learn about setState in doc. You can force re-render using forceUpdate(), but it is not advisable. Alternatively, you can do this.setState(this.state)

4
votes

Actually I do not know when react re-renders page and which part of the page it renders ?

It renders the page once, then it only rerenders a component where the state was changed using setState. If that rerender adds new elements, they get rendered too.

How can I force React to re-render somewhere in the page

Move the data that changes into the state and call setState if it changes.