Categories
React Tips

React Tips — Body Styles, Modal, Compare Props, and Reset Forms

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

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.

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 .

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.

Creating a Custom Function in React Component

We can create a custom function within a React component.

For instance, we can write:

class App extends React.Component {

  log(message) {
    console.log(message);
  }

  handleClick(e) {
    this.log("button clicked");
  }

  componentDidMount() {
    this.log("component mounted");
  }

  render() {
    return <button onClick={this.handleClick.bind(this)}>click me</button>;
    }
}

We have the log method that runs console.log .

We can call it from other method with this.log .

How to Fetch Data When a React Component Prop Changes

To fetch data when a React component changes, we can add the componentDidUpdate method to our class component.

It takes a parameter for the previous prop value.

We can use that to compare with the current prop value to determine if we want to fetch data or not.

If they’re different, then we do the fetching.

For instance, we can write:

class App extends Component {
  componentDidMount() {
    this.fetchData();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.params.id !== this.props.params.id) {
      this.fetchData();
    }
  }

  fetchData() {
    this.props.fetchData(this.props.params.id);
  }
}

We have the componentDidUpdate method that has the prevProps parameter.

We compare the id from prevProps to the id in the current prop to determine if we want to call fetchData .

Conclusion

We can set body styles with plain JavaScript.

A React modal can be created with portals.

There are various ways to reset a form.

We can compare the value of the old and new props with componentDidUpdate .

Leave a Reply

Your email address will not be published. Required fields are marked *