« Back to blog

Make a blog for create-react-app in 10 lines of code

If you're using create-react-app - we can create a Markdown (Jekyll style) blog in 10 lines of code.

Assumptions

  1. you're using create-react-app 2.4.3 and react-router 3.2
  2. Jekyll style (so create a _posts directory)

1. Install dependencies

npm install -g create-react-app@1.4.3
create-react-app react-blog
cd react-blog
npm install --save --save-exact react-scripts@1.0.17
npm install --save react-router@3.2.0 markdown-with-front-matter-loader@0.1.0 github-markdown-css@2.9.0
npm start

step1

2. Dynamically require all blogs (Webpack)

// eslint-disable-next-line import/no-webpack-loader-syntax
const webpackRequireContext = require.context('!markdown-with-front-matter-loader!./_posts', false, /.md$/);
const blogs = webpackRequireContext.keys().reduce((memo, fileName) => memo.set(fileName.match(/.\/([^.]+).*/)[1], webpackRequireContext(fileName)), new Map())

step2

3. Create UI

// eslint-disable-next-line import/first
import 'github-markdown-css';
const blogIndex = (blogs) => () => <ul>{[...blogs.keys()].map(path => <li key={path}><Link to={'/'+path}>{blogs.get(path).title || path}</Link></li>)}</ul>;
const blogWrapper = ({ __content }) => () => <div><Link to='/'>« Back to blog</Link><hr /><div className='markdown-body' dangerouslySetInnerHTML={{__html: __content}}></div></div>;

step3

4. Create react-router routes

// eslint-disable-next-line import/first
import { Link, IndexRoute, Router, Route, browserHistory } from 'react-router';
const reactRoutes = [<IndexRoute key='index' component={blogIndex(blogs)} />].concat([...blogs.keys()].map(path => <Route key={path} path={path} component={blogWrapper(blogs.get(path))} />));

5. Integrate within your react-router config

<Route path="/">{reactRoutes}</Route>

6. Final integration

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/">{reactRoutes}</Route>
  </Router>,
  document.getElementById('root')
);

step4

7. Now create a _posts directory and write a blog post in Markdown

step5

8. What it looks like

blog-index

blog-post

9.

get it here: https://github.com/sanfrancesco/create-react-app-blog

Hosted on Roast.io