Skip to content

Instantly share code, notes, and snippets.

@nsfmc
Last active January 26, 2016 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsfmc/d2dd0109c955f0f5a127 to your computer and use it in GitHub Desktop.
Save nsfmc/d2dd0109c955f0f5a127 to your computer and use it in GitHub Desktop.
A bad idea

Nest

a simple higher order react component to create nested css trees. there's lots that this doesn't do, but if you have ever needed to create <div class=foo><div class=bar><ActualElement /></></> this will take care of doing that for you.

it does not understand css, it can't set multiple classes on a single element, it's very dumb for now.

Nest(classlist: string): Function returns a function Nested(ChildElement: ReactElement): ReactElement

where the classlist looks like 'a b c' and returns a function that behaves like

(child) => <div class="a">
  <div class="b">
    <div class="c">
      {child}
    </div>
  </div>
</div>
var Nest = (classlist) => {
// classlist = 'foo bar baz'
let classes = classlist.split(' ');
classes.reverse();
let nestReducer = (prev, current) => <div className={current}>{prev}</div>;
return (el) => (props) => classes.reduce(nestReducer, el)
}
var Hello = React.createClass({
render: function() {
let E = Nest('foo bar baz')(<span>bye</span>); // the span will be blue
return <div><E /></div>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
.foo .bar .baz span {
color: blue;
}
@nsfmc
Copy link
Author

nsfmc commented Jan 26, 2016

this is really only useful if you are trying to recreate some complexly nested div hierarchy but don't feel like actually writing out the topmost components. otherwise this is needlessly obtuse

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment