manas
manas

Reputation: 6400

react-router Link doesn't render href attribute with server side rendering?

I have a expressjs app with the following code, what i am trying to do is to render a react component named Hello with the request to "/". Inside Hello component i am using two react-router Links, but these two Links doesn't render the href attributes.

I am using here react-router 2

Server.js file

var express = require("express");
var app = express();
var React = require("react");
var ReactDOM = require("react-dom/server");

var Hello = React.createFactory(require("./js/components/Hello"));
// The above is a reference to pre-compiled Hello.jsx to Hello.js using babel

app.set("view engine", "ejs");
app.set("views", "./views");

app.use(express.static("./public"));

app.get("/", function (req, res) {
    res.render("Home",{data:ReactDOM.renderToString(Hello())});
});


app.listen(app.get("port"), function () {
    console.log("server started on port " + app.get("port"));
});

Hello.jsx File

var React = require("react");
var Link = require("react-router/lib/Link");

var Hello = React.createClass({
   callMe:function(){
       alert("Hurray");
   },
   componentWillMount:function(){
        console.log("componentWillMount fired");
   },
   render:function(){
     //  console.log(this);
       return(
           <div>
                <h2 onClick={this.callMe}>Hello Boom Boom {this.props.name}</h2>
                <Link to="/">Home</Link>
                <Link to="/about">About</Link>
                // above two Links rendering anchor tags without href attribute
           </div>
       );
   }
});


module.exports = Hello;

Home.ejs File

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

</head>
<body>
    <h2>Welcome to home page</h2>
    <div id="container">
        <%- data %>
    </div>

</body>
</html>

in browser output

Upvotes: 3

Views: 2117

Answers (2)

Oli Beatson
Oli Beatson

Reputation: 841

I just had the same problem, and the thing I was missing was the surrounding <RouterContext>. <Link> components seem to have an empty href attribute when not inside of a <Router> or appropriate react-router environment. I improved the routing in the SSR code (I was doing a weird partial solution) and the links started appearing.

Upvotes: -1

taion
taion

Reputation: 2837

Please consult the React Router server rendering guide: https://github.com/reactjs/react-router/blob/master/docs/guides/ServerRendering.md

You need to render your components in an appropriate routing context for <Link> to generate URLs.

Upvotes: 2

Related Questions