Skip to content

Instantly share code, notes, and snippets.

@developit
Last active December 5, 2017 16:35
Show Gist options
  • Save developit/9f547d32b96f879b259be399a5dc0f01 to your computer and use it in GitHub Desktop.
Save developit/9f547d32b96f879b259be399a5dc0f01 to your computer and use it in GitHub Desktop.
A couple of variants for preact split points
import { h, Component } from 'preact';
/**
* <SplitPoint load={require('bundle?lazy!./foo')} fallbackContent={(
* <div class="loading" />
* )} />
*/
class SplitPoint extends Component {
componentWillMount() {
let cb = this.linkState('child'),
r = this.props.load(cb);
if (r.then) r.then(cb);
}
render({ load, fallbackContent, ...props }, { child }) {
return child ? h(child, props) : fallbackContent || null;
}
}
class SplitPoint extends Component {
componentWillMount() {
let cb = this.linkState('child'),
r = this.props.load();
r.then ? r.then(cb) : cb(r);
}
render(props, { child }) {
return child ? h(child, props) : null;
}
}
class Split extends Component {
render({ load, ...props }, { child }) {
if (!child && !this.child) {
let c = this.child = load();
c.then ? c.then(this.linkState('child')) : (child = c);
}
return child ? h(child, props) : null;
}
}
@MatteoWebDeveloper
Copy link

MatteoWebDeveloper commented Jan 6, 2017

I am trying the first example.

Are you using bundle-loader?

Because I have this error message: "Cannot read property 'then' of undefined"

if I console this.props.load it return:

function (cb) {
	__webpack_require__.e/* nsure */(1, function(require) {
		cb(__webpack_require__(440));
	});
}

and this.props.load(cb) return: undefined

@MatteoWebDeveloper
Copy link

MatteoWebDeveloper commented Jan 7, 2017

Now it looks like it's working:

export default class SplitCode extends Component {
	componentWillMount() {
            this.props.load((file) => {
                this.setState({ child: file.default });
            });
	}
	render({ load, fallbackContent, ...props }, { child }) {
            return child ? h(child, props) : fallbackContent || null;
	}
}

@diegochavez
Copy link

Works, using setState but just with page reload not with router link. with linkState demo doesn't work.

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