diff --git a/README.md b/README.md index 5a501e9..f22db9c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_680 TILs and counting..._ +_681 TILs and counting..._ --- @@ -473,6 +473,7 @@ _680 TILs and counting..._ - [Dynamically Create HTML Elements](react/dynamically-create-html-elements.md) - [Enforce Specific Values With PropTypes](react/enforce-specific-values-with-proptypes.md) - [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md) +- [Forcing A Child Remount With The Key Prop](react/forcing-a-child-remount-with-the-key-prop.md) - [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md) - [Inline Style Attributes Should Be Camel Cased](react/inline-style-attributes-should-be-camel-cased.md) - [Mapping Over One Or Many Children](react/mapping-over-one-or-many-children.md) diff --git a/react/forcing-a-child-remount-with-the-key-prop.md b/react/forcing-a-child-remount-with-the-key-prop.md new file mode 100644 index 0000000..9b8a0a8 --- /dev/null +++ b/react/forcing-a-child-remount-with-the-key-prop.md @@ -0,0 +1,41 @@ +# Forcing A Child Remount With The Key Prop + +There are a couple `prop` names that have reserved usage in React. One of +those is `key`. We generally use `key` when we are rendering a list of +things. It is a way of uniquely identifying each element in a list so that +React minimizes re-rendering when parts of the list change. + +We can flip this on its head and utilize `key` as a way of forcing a remount +and re-render of a child component. + +Imagine I have a component that does a number of things including rendering +a component with some internal state, such as a counter. + +```javascript +class MyComponent extends React.Component { + state = { + remountKey: (new Date()).getTime(), + } + + resetCounter = () => { + this.setState({ + remountKey: (new Date()).getTime(), + }); + } + + render() { + return ( +
+ {/* some other stuff in my component */} + + + +
+ ); + } +} +``` + +I can force this `Counter` component to remount, thus resetting its state +simply by passing it a new `key` value. The `button` can trigger this by +updating the `remountKey` value.