Reputation: 79
I have a general question about how ReactJs Render()
functionality. Say we have some HTML within index.html
<section id="Hello">
<h1>Hello world</h1>
<p>Something something Darkside</p>
</section>
And a react Class
var Hello = React.createClass({
render: function() {
...
}
});
Can we pass the contents of the #Hello
into the react class to render, instead of writing JSX?
And also, is it possible to have this, in the index.html source
<Hello>
<h1>Hello world</h1>
<p>Something something Darkside</p>
</Hello>
and automatically connect it to a React Class
var Hello = React.createClass({
render: function() {
...
}
});
Here <Hello />
connects to the class automatically?
This would be similar to Angulars <ng-content />
and initialisation of objects
Upvotes: 0
Views: 98
Reputation: 1294
If your goal in the first question solely to have react render the #Hello html without using jsx then you will need to use the plain JavaScript REACT syntax.
Something like this:
<body>
<div id='container'></div>
<script>
var Hello = React.createClass({
render: function() {
return React.createElement(
'section',
{ id: 'Hello' },
React.createElement('h1',null, 'Hello world'),
React.createElement('p',null,'Something something Darkside')
);
}
});
ReactDOM.render(React.createElement(Hello,null),document.getElementById('container'));
</script>
</body>
if you like you can use something like babel to generate plain javascript from jsx for you. they have an interactive tool here where you can try it out.
For your question "Can the ReactDOM.render read the children properties of html within the index.html?". Assuming you are asking if you can just have ReactDOM.render return the html of #Hello. The answer is no you cannot.
ReactDOM.render method expects you to return a ReactComponent
So something like this would be invalid:
<section id="Hello">
<h1>Hello world</h1>
<p>Something something Darkside</p>
</section>
<script>
var Hello = React.createClass({
render: function() {
return $('#Hello').html(); //<-- Error here
}
});
</script>
gives an error:
A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.
Upvotes: 0
Reputation: 87
I haven't run the code snippet to test yet but based on my knowledge. You can do something like:
<Hello id='hello-id'></Hello>
<script type='text/babel'>
var Hello = React.createClass({
render: function() {
return(
<div>
{this.props.children}
</div>
);
}
});
ReactDOM.render(
<Hello>
<h1>Hello world</h1>
<p>Something something Darkside</p>
</Hello>,
document.getElementById('hello-id')
);
</script>
Result should be:
<Hello id='hello-id'>
<div>
<h1>Hello world</h1>
<p>Something something Darkside</p>
</div>
</Hello>
this.props.children
(Children props) can be used to pass the children elements onto react component.
The Hello
in ReactDOM.render
is connected to the Hello
class. But <Hello/>
in the html source is not. It's just the custom html tag.
Upvotes: 1