Reset initial state in React + ES6

Viewed 41405

I have a class, ElementBuilder below, and when the user saves the Element they've built, I want the state to reset to the values below.

I have some functions in this class that I haven't provided but that change the state of title, size, and color.

In ES 5, I would have a getInitialState function on my class and could call this.getInitialState() in a function.

This element lives in my app for the lifecycle of a logged in user and I want the default values to always be the same regardless of past usage.

How do I achieve this without writing a function that sets an object of default values (or maybe that's the answer)? thanks!

class ElementBuilder extends Component {
    constructor(props) {
        super(props);

        this.state = {
            title: 'Testing,
            size: 100,
            color: '#4d96ce',
        };
    }

    resetBuilder() {
        this.setState({ this.getInitialState() });
    }
}
4 Answers

Use an High Order Component to clear component state (rerender)

Exemple Element.jsx :

// Target ----- //

class Element extends Component {

  constructor(props){
    super(props)
    const {
        initState = {}
    } = props
    this.state = {initState}
  }

  render() {
    return (
        <div className="element-x">
            {...}
        </div>
    )
  }
}

// Target Manager ----- //

class ElementMgr extends Component {

    constructor(props){
        super(props)
        const {
            hash = 0
        } = props
        this.state = {
            hash, // hash is a post.id 
            load: false
        }
    }

    render() {
        const {load} = this.state
        if (load) {
            return (<div className="element-x"/>)
        } else {
            return (<Element {...this.props}/>)
        }
    }

    componentWillReceiveProps(nextProps) {
        const {hash = 0} = nextProps
        if (hash !== this.state.hash) {
            this.setState({load:true})
            setTimeout(() => this.setState({
                hash,
                load:false
            }),0)
        }
    }
}

export default ElementMgr
Related