This is a code for a simple counter.
However, when i Render the view i don't get any output. Please tell me what is wrong with the code.
The button is pressed and a counter is incremented and is rendered onto the screen.
var Title = React.createClass({
getInitialState : function(){
return {count:0};
},
increment : function(){
this.setState({count:this.state.count+this.props.incVal});
},
render: function() {
return (
<div>
<h1 >Count : {this.state.count}< /h1>
<button onClick={this.increment} >Increment</button>
</div>
);
}
});
var MultiButton = React.createClass({
render : function (){
return(
<Title incVal={1}/>
<Title incVal={5}/>
);
}
});
ReactDOM.render( <MultiButton /> ,
document.getElementById('example')
);
You cannot return more than one elements from the React class. If you have more than one elements wrap them in a single div like
var MultiButton = React.createClass({
render : function (){
return(
<div>
<Title incVal={1}/>
<Title incVal={5}/>
</div>
);
}
});
From the official documentation.
<div>
Here is a list:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
A React component can't return multiple React elements, but a single
JSX expression can have multiple children, so if you want a component
to render multiple things you can wrap it in a div like this.
Change from
var MultiButton = React.createClass(
{
render: function () {
return (
<Title incVal={1}/>
<Title incVal={5}/>
);
}
}
);
to
var MultiButton = React.createClass(
{
render: function () {
return (
<div>
<Title incVal={1}/>
<Title incVal={5}/>
</div>
);
}
}
);
var Title = React.createClass({
getInitialState : function(){
return {count:0};
},
increment : function(){
this.setState({count:this.state.count+this.props.incVal});
},
render: function() {
return (
<div>
<h1 >Count : {this.state.count}< /h1>
<button onClick={this.increment.bind(this)} >Increment</button>
</div>
);
}
});
var MultiButton = React.createClass({
render : function (){
return(
<Title incVal={1}/>
);
}
});
ReactDOM.render( <MultiButton /> ,
document.getElementById('example')
);