Skip to content

Commit

Permalink
utils: add IdContext
Browse files Browse the repository at this point in the history
This allows components to use deterministic IDs so that server and client markup matches up
  • Loading branch information
ryanflorence committed Sep 4, 2018
1 parent fc45afd commit 44214ae
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions packages/utils/src/lib/IdContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React, { createContext } from "react";

// most things that we auto-id aren't server rendered, and are rendered into
// portals anyway, so we can get away with random ids in a default context. If
// people need to server render with auto-ids, they can wrap their app in an
// IdProvider
let genId = () =>
Math.random()
.toString(32)
.substr(2, 6);

let IdContext = createContext(genId);

// Apps can wrap their app in this to get the same IDs on the server and the
// client
class Provider extends React.Component {
id = 0;

genId = () => {
return ++this.id;
};

render() {
return (
<IdContext.Provider value={this.genId}>
{this.props.children}
</IdContext.Provider>
);
}
}

let { Consumer } = IdContext;

export { Provider, Consumer };

0 comments on commit 44214ae

Please sign in to comment.