Categories
React Answers

How to Create a Custom Function in a React Component ?

Sometimes, we want to create a custom function in a React component.

In this article, we’ll look at how to create a custom function in a React component.

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 .

Conclusion

We can create a custom function within a React component.

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.