Hemantha Dhanushka
Hemantha Dhanushka

Reputation: 163

Easy way to set default state values in React JS component

Is there any easy way to set component's state convert to default state.

Normally I create a function for this by setting a default values like below. Is there other way instead of this?

import React, { Component } from 'react';

class Person extends Component {
    state = {
        firstName: null,
        lastName : null,
        age      : null,
        address  : null,
    }

    // Set state to default state
    setDefaultState = () => {
        this.setState({
            firstName: null,
            lastName : null,
            age      : null,
            address  : null,
        });
    }

    render() {
        return(
            <div>
                Person Component
            </div>
        );
    }
}

export default Person;

Is there any pre-defined function for this in react js.

Thanks in Advance. :)

Upvotes: 0

Views: 16969

Answers (1)

cuongtd
cuongtd

Reputation: 3182

this is an approach

initialState = {
    firstName: null,
    lastName : null,
    age      : null,
    address  : null,
}

class Person extends Component {
    state = {
        ...initialState
    }

    // Set state to default state
    setDefaultState = () => {
        this.setState({
            ...initialState
        });
    }

Upvotes: 2

Related Questions