I'm trying to setup a preact-cli environment where the content and the routes are defined by a CMS but am struggling to understand how to implement this. Is this even possible to do? At the moment all of the components and routes are hard coded in the src files, how can this be made dynamic?
Hi there! Unfortunately, preact-cli can only prerender _static_ pages. You'd have to setup your dynamic pages to fetch data from your CMS API in the componentWillMount cycle of your dynamic route.
For a quick example:
<div id="app">
<Header />
<Router onChange={this.handleRoute}>
<Home path="/" />
<About path="/about" />
<Posts path="/posts/:slug" />
</Router>
</div>
Both Home and About can be pre-rendered. Your Posts component will look something like this:
export default class Posts extends Component {
state = { data:{} }
componentWillMount() {
fetch(`/api/posts/${ this.props.slug }`)
.then(res => res.json()).then(data => this.setState({ data }));
}
// ...
render(props, state) {
const data = state.data;
return (
<div id="post">
<h1 className="post__title">{ data.title }</h1>
<!-- etc -->
</div>
)
}
}
Hope that helps!
Most helpful comment
Hi there! Unfortunately,
preact-clican only prerender _static_ pages. You'd have to setup your dynamic pages tofetchdata from your CMS API in thecomponentWillMountcycle of your dynamic route.For a quick example:
Both
HomeandAboutcan be pre-rendered. YourPostscomponent will look something like this:Hope that helps!