Skip to content

Instantly share code, notes, and snippets.

@akoskm
Last active September 3, 2019 09:02
Show Gist options
  • Save akoskm/71c234a90dc39823eacd3bb6426164e4 to your computer and use it in GitHub Desktop.
Save akoskm/71c234a90dc39823eacd3bb6426164e4 to your computer and use it in GitHub Desktop.
Use React Context to DRY up your components
<TableContext.Provider value={product}>
<Table
products={products}
onProductChange={handleProductChange}
/>
<Sidebar />
</TableContext.Provider>
<Table
selectedProduct={product}
products={products}
onProductChange={handleProductChange}
/>
<Sidebar product={product} />
const Sidebar = () => {
const product = React.useContext(TableContext);
return (
<>
<h3>{product.name}</h3>
<p>ID: {product.id}</p>
<p>SKU: {product.sku}</p>
</>
);
}
export default Sidebar;
const Sidebar = () => (
<div className="sidebar">
<DetailsPanel />
<DimensionsPanel />
</div>
);
const Sidebar = ({ product }) => (
<div className="sidebar">
<DetailsPanel product={product} />
<DimensionsPanel product={product} />
</div>
);
const Sidebar = ({ product }) => (
<div className="sidebar">
<h3>{product.name}</h3>
<p>ID: {product.id}</p>
<p>SKU: {product.sku}</p>
</div>
);
export default Sidebar;
const value = React.useContext(TableContext);
const TableContext = React.createContext();
TableContext.Provider.propTypes = {
value: PropTypes.shape({
id: PropTypes.string,
name: PropTypes.string,
sku: PropTypes.string,
}),
}
export default TableContext;
const TableContext = React.createContext();
export default TableContext;
const Table = ({ selectedProduct, products, onProductChange }) => (
<tbody>
{products.map(currProduct => (
<TableRow
selected={isSelected(currProduct, selectedProduct)}
key={currProduct.id}
product={currProduct}
onProductChange={onProductChange}
/>
))}
</tbody>
);
export default Table;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment