8. React Component Properties
Let’s pass some properties to the HelloWorld
component now!
In index.jsx
, we’ll simply add an attribute to the <HelloWorld>
tag.
var http = require('http') , React = require('react') , HelloWorld = require('./Components/HelloWorld') http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}) res.end( React.renderToString( <html> <head> <title>Hello World</title> </head> <body> <HelloWorld from="index.jsx on the server" /> </body> </html> ) ) }).listen(1337) console.log('Server running at http://localhost:1337/')
Within the Components/HelloWorld.jsx
, we’ll make use of that from
property.
var React = require('react') module.exports = React.createClass({ render: function() { return ( <div> <div> This is from the HelloWorld.jsx component render function. </div> <div> Rendered from: {this.props.from} </div> </div> ) } })
There’s a noteworthy React/JSX tip to talk about here: Parse Error: “Adjacent JSX elements must be wrapped in an enclosing tag.”
In the HelloWorld.jsx
file, I initially used the following code, and it resulted in this Adjacent JSX elements error.
var React = require('react') module.exports = React.createClass({ render: function() { return ( <div> This is from the HelloWorld.jsx component render function. </div> <div> Rendered from: {this.props.from} </div> ) } })
It took a few minutes to understand, but what was happening is the HelloWorld.jsx
file’s return statement had two adjacent <div>
tags. This syntax is unsupported; as the error message explains, the output must be wrapped in an outer element–I just wrapped the two <div>
elements in an outer <div>
, as seen above in the working code.