Haijin
Haijin

Reputation: 2666

Is there a way to externally reset a react component to its original state

I am current working with some complex stateful React components I installed through npm. For example, a react-bootstrap-table component. It accept data through its props. But it keeps a lots of states of its own, for example, which row is currently selected. I am adding a button, on clicking I would like to clear all the selected row information. Not having access to any API that can do that, I am wondering if I can totally reset the table component.

Right now I use a wrapper component that render the table based on a flag. It looks like:

class wrapper extends React.component{

  render(){
    if(this.props.flag==true) return <React-Table />;
    else return null;
      }
}

Now by toggling the flag, I can force a re-render of the table component with its original state.

I am wondering if there is a more straightforward way to do this?

Upvotes: 1

Views: 1552

Answers (2)

Haijin
Haijin

Reputation: 2666

To give a more general answer,

React does not have a general way to reset a component externally, the component should provide it if it's necessary. There are 2 ways for parent component to communicate with child component, through props, or not frequently, using ref to directly call a child method. Resetting is using the second way.

For react-bootstrap-table, there are reset() and cleanSelected() method you can call. How to call child component method.

Upvotes: 0

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19130

After searching the react-boostrap-table API, it found a method reset (see docs):

Call reset to clean all the status on the table currently.

this.refs.table.reset();  // this.refs.table is a ref for BootstrapTable

Upvotes: 1

Related Questions