u111937
u111937

Reputation: 287

How to pass Markdown file as this.props in React?

I'm building a site in React using Redux, and my goal is to have a /pages folder full of markdown files that'll represent a pages content.

I have a React Container (smart) and a React Component (dumb) that'll be used to render the content. My thinking is that I'll import the markdown files to the parent container and pass them down to the child component to render them in the browser. I know I'll need to use something like markdown-it to convert the MD to HTML and maybe I'll need to use that in the child component.

My questions are:

1) How do I pass in markdown files from parent to child using this.props? 2) Am I on the right track? Is this the right way to go about it?

Here are my components:

Page Parent Container

import React from 'react'
import SamplePage from './../components/SamplePage'

export default class Page extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return (
      <section>
        <SamplePage />
      </section>
    )
  }
}

SamplePage Child Component

import React from 'react'
import { Link } from 'react-router'

export default class SamplePage extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return (
      <div className="page-container">
        <Link to="/" className="previous-link">Go Back Home</Link>

        // I want to render the MD here using {this.props.markdown}

      </div>
    )
  }
}

Upvotes: 2

Views: 2184

Answers (1)

probablyup
probablyup

Reputation: 8134

A few things:

1) I recommend using a Markdown to JSX parser to keep your templating safe (otherwise you'd likely have to use dangerouslySetInnerHtml)

2) I'd run this parser during build time, so everything is already ready to go. If you're using webpack or browserify, you can add a custom loader/transformer function to look for *.md files being required and run it through the parser.

3) The parsed markdown is then simple JSX and can be required & dropped into your existing component as you've done above.

Upvotes: 1

Related Questions