Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTML Wrapper: bind react router history to links under innerHTML #244

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 50 additions & 13 deletions lib/isomorphic/wrappers/html.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,55 @@
import React, { PropTypes } from 'react'
import React, { Component } from 'react'
import { browserHistory } from 'react-router'

module.exports = React.createClass({
propTypes: {
page: PropTypes.shape({
data: PropTypes.shape({
body: PropTypes.string.isRequired,
}),
}),
},
export default class HtmlWrapper extends Component {

propTypes = {
router: React.PropTypes.object,
}

componentDidMount () {
this.refs.holder.addEventListener( 'click', this.onNodeClick )
}

componentWillUnmount () {
this.refs.holder.removeEventListener( 'click', this.onNodeClick )
}

onNodeClick = ( e ) => {
const node = e.target

// Only accept links
if ( node.tagName !== 'A' ) {
return
}

const href = node.getAttribute( 'href' )

// That are pointing to an internal page
// All internal links should have a slash on the start and on the end
// Example: /about/me/
if ( ! href.match( /^\/.*\/$/ ) ) {
return
}

// That doesn't have a data-react attribute
if ( node.getAttribute( 'data-react' ) ) {
return
}

// Seems that we've found a link that isn't being managed by react
// Lets prevent browser default and propagation
e.preventDefault()

// And use react-router history instead
browserHistory.push( node.href )
}

render () {
const html = this.props.page.data.body
const post = this.props.route.page.data

return (
<div dangerouslySetInnerHTML={{ __html: html }} />
<div ref="holder" dangerouslySetInnerHTML={{ __html: post.body }} />
)
},
})
}
}