I have simple nested React component. I am nesting HelloWorld
inside Button
. But I would like to mount HelloWorld on a specific div (ie.on 'hello' id). Is it possible?
index.html
<body>
<div id="hello"></div>
<div id="btn"></div>
</body>
jsx
var HelloWorld = React.createClass({
render: function(){
return (
<b>Hello World!</b>
)
}
});
var options={
txt: "I'm Getting there!",
counter: 10
}
var Button = React.createClass({
handleClick: function(){
alert('you clicked');
},
render: function(){
return <div>
<button onClick={this.handleClick}>{this.props.options.txt}</button>
<i>{this.props.options.counter}</i>
<HelloWorld/> //can I mount this on hello?
</div>
}
});
ReactDOM.render(<Button options={options}/>, document.getElementById("btn"));
Yes you can, but not directly as in your code: You cannot mount a react component outside of the root react container.
Option 1 (this is more or less standard practice)
Create 1 react container and mount everything in there:
index.html:
<body>
<div id="myApp"></div>
</body>
App.js:
var MyApp = React.createClass({
render: function(){
return (
<div>
<HelloWorld />
<Button options={this.props.options} />
</div>
)
}
});
// other code unchanged..
ReactDOM.render(<MyApp options={options}/>, document.getElementById("myApp"));
Option 2 (not recommended) Alternatively, you can create 2 completely separate react containers. Please note that these react containers cannot communicate with eachother in react-framework language.
(index.html unchanged).
app.js
// (other code unchanged) ...
ReactDOM.render(<HelloWorld />, document.getElementById("hello"));
ReactDOM.render(<Button options={options}/>, document.getElementById("btn"));
PS: I left out the option var in the examples code, to focus on your question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.