Skip to content

Instantly share code, notes, and snippets.

@dmiller9911
Created January 30, 2017 02:42
Show Gist options
  • Save dmiller9911/83c98982ff21a3ddf6c1c11187e9171b to your computer and use it in GitHub Desktop.
Save dmiller9911/83c98982ff21a3ddf6c1c11187e9171b to your computer and use it in GitHub Desktop.
React Slot Example
import React from 'react';
import ReactDOM from 'react-dom';
function Slot({ children, slot }) {
let slottedChild = null; // Default to null since react can render null if a slot isn't found
// Iterate over children to find the slot needed
React.children.forEach(children, (child) => {
if (!React.isValidElement(child)) { // Check that it is a valid react element.
return; // Return since we can't do anything with a child without props.
}
if (child.props['data-slot'] === slot) { //Verify it matches the slot we are looking for.
slottedChild = React.cloneElement(child); // Clone it and set it to the slotted child
}
});
return slottedChild;
}
function Slotted({ children }) {
return (
<div>
<header>
<Slot slot="header">{children}</Slot>
</header>
<main>
<Slot slot="main">{children}</Slot>
</main>
<footer>
<Slot slot="footer">{children}</Slot>
</footer>
</div>
);
}
ReactDOM.render(
<Slotted>
<div data-slot="header">Header Content</div>
<div data-slot="main">Main Body</div>
<div data-slot="footer">Footer Content</div>
</Slotted>
);
/* Renders:
<div>
<header>
<div data-slot="header">Header Content</div>
</header>
<main>
<div data-slot="main">Main Body</div>
</main>
<footer>
<div data-slot="footer">Footer Content</div>
</footer>
</div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment