Guy Guy - 1 year ago 278
React JSX Question

Clearing state es6 React

I am trying to clear a components

but can't find a reference for the es6 syntax. I was using:


however this does not work with the es6 class syntax.

How would I achieve the same result?

Answer Source

To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.

const initialState = {
    /* etc */

class MyComponent extends Component {
    constructor(props) {
        this.state = initialState;
    reset() {
    /* etc */

Beware that the line this.state = initialState; requires you never to mutate your state, otherwise you'll pollute initialState and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState in the constructor. (Or make initialState a function, as per getInitialState().)

Finally, I'd recommend you use setState() and not replaceState().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download