Preact-cli: Dynamic routes and content from CMS

Created on 20 Jul 2017  路  1Comment  路  Source: preactjs/preact-cli

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?

Most helpful comment

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!

>All comments

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!

Was this page helpful?
0 / 5 - 0 ratings