Categories
React Answers

How to Clear and Reset Form Input Fields in a React App?

Sometimes, we want to clear and reset form input fields in our React app.

In this article, we’ll look at how to clear and reset form input fields in our React app.

Clear and Reset Form Input Fields

If we have a form that has a onSubmit prop set to a submit handler function. we can call reset to reset the form values.

For instance, if we have:

<form onSubmit={this.handleSubmit.bind(this)}>
  {/* ... */}
</form>

Then our handleSubmit method can be written as:

handleSubmit(e){
  e.preventDefault();
  e.target.reset();
}

We call reset to reset all the fields in the form.

This works for uncontrolled form fields.

If we have controlled form fields, then we’ve to reset the state to the original values.

For example, we can write:

import React, { Component } from 'react'

class NameForm extends Component {
  initialState = { name: '' }

  state = this.initialState

  handleFormReset = () => {
    this.setState(() => this.initialState)
  }

  onChange = (e) => {
    this.setState({ name: e.target.value });
  }

  render() {
    return (
      <form onReset={this.handleFormReset}>
        <div>
          <label htmlFor="name">name</label>
          <input
            type="text"
            placeholder="name"
            name="name"
            value={this.state.name}
            onChange={this.onChange}
          />
        </div>
        <div>
          <input
            type="submit"
            value="Submit"
          />
          <input
            type="reset"
            value="Reset"
          />
        </div>
      </form>
    )
  }
}

We can set the onReset prop of the form to the handleFormReset method so that we set the form values back to the original values by setting the state to the initialState .

Since we have an input element with type set to reset , when that’s clicked, the function that we passed into the onReset prop will run.

Conclusion

If we have a form that has a onSubmit prop set to a submit handler function. we can call reset to reset the form values.

Categories
React Answers

How to Create a Modal in a React App?

Sometimes, we want to add a modal into our React app.

In this article, we’ll look at how to add a modal into our React app.

Create a React Modal

We can use React’s portal feature to render our component anywhere.

This way, we can create a modal that’s attached to whatever element we want.

For instance, we can write:

const ModalComponent = ({ children, onClose }) => {
  return createPortal(
    <div className="modal" onClick={onClose}>
      {children}
    </div>,
    document.getElementById("portal")
  );
};

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      showModal: false
    };
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ showModal: true })}>
          Open modal
        </button>
        {this.state.modalOpen && (
          <ModalComponent onClose={() => this.setState({ showModal: false })}>
            <h1>modal content</h1>
          </ModalComponent>
        )}
      </div>
    );
  }
}

We create a ModalComponent component to let us nest content inside it.

We can do that since it takes the children component.

All we have to do is render the children prop.

We use React’s createPortal method to let us render the div anywhere we want.

In App , we created a button to let us open the modal.

To do that, we set the showModal state to true .

We also created a function that we pass into the onClose prop of ModalComponent so that showModal can be set to false .

This will close the modal since ModalComponent is only shown when showModal is true .

Conclusion

We can use React’s portal feature to render our component anywhere.

Categories
React Answers

How to Set Body Styles with React?

Sometimes, we want to set body styles within our React app.

In this article, we’ll look at how to set body styles within our React app.

Set Body Styles with React

Within our React component, we can set the body style with plain JavaScript.

For instance, we can write:

componentDidMount(){
  document.body.style.backgroundColor = "green";
}

componentWillUnmount(){
  document.body.style.backgroundColor = null;
}

We set the document.body.style.backgroundColor property to set the background color.

componentDidMount lets us run code when the component mounts.

componentWillUnmount runs when the component unmounts.

Conclusion

Within our React component, we can set the body style with plain JavaScript.

Categories
React Answers

How to Set State Inside a React useEffect Hook Callback?

Sometimes, we want to set states inside the React useEffect hook callback.

In this article, we’ll look at how to set states inside the React useEffect hook callback.

Set State Inside a useEffect Hook

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

For instance, we write:

useEffect(() => {
  setState(state => ({ ...state, foo: props.foo }));
}, [props.foo]);

useEffect(() => {
  setState(state => ({ ...state, bar: props.bar }));
}, [props.bar]);

We watch the props properties by passing them into the array.

Then we merge the items into the state object that we return in the callback.

Conclusion

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

Categories
React Answers

How to Reduce State Updater Calls in React Function Component?

To optimize the performance of our React app, we should find ways to reduce state updater calls in React function components.

In this article, we’ll find ways to reduce state updater calls in React function components.

Reduce State Updater Calls in Function Component

To reduce state updater calls in a function component, we can use one state to store an object.

And we can use the state update function to update the object instead of using multiple state updater functions to update individual values.

For instance, we can write:

const {useState, useEffect} = React;

function App() {
  const [userRequest, setUserRequest] = useState({
    loading: false,
    user: null,
  });

  useEffect(() => {
    setUserRequest({ loading: true });
    fetch('https://randomuser.me/api/')
      .then(res => res.json())
      .then(data => {
        const [user] = data.results;
        setUserRequest({
          loading: false,
          user
        });
      });
  }, []);

  const { loading, user } = userRequest;

  return (
    <div>
      {loading && 'Loading...'}
      {user && user.name.first}
    </div>
  );
}

We have the setUserTequest function that updates a state that’s stored as an object.

It has the loading and user properties.

loading is the boolean to indicate loading.

user has the user data.

We set the loading property with setUserRequest when the useEffect callback first runs.

And in the then callback, we called our API.

And then we get the data and render it afterward.

The empty array ensures that the callback only loads when the component mounts.

Conclusion

To reduce state updater calls in a function component, we can use one state to store an object.

And we can use the state update function to update the object instead of using multiple state updater functions to update individual values