Reputation: 366
I'm learning react and I came across some nice examples I'm learning from, but it seems their syntax is no longer supported by react v15
initial code:
NewGameButton = React.createClass({
render: function() {
return React.DOM.div({
className: 'tic-tac-toe--new-game-button',
children: 'New game',
onMouseUp: this.props.onClick
});
}
});
from what I had learned, I tried to rewrite this piece of code to es6:
class NewGameButton extends React.Component {
render() {
return (
<div>
.. ???
</div>
);
}
}
now I'm stuck, I found out that class name module is deprecated and I have no idea how to rewrite this to make it work
thanks!
Upvotes: 1
Views: 119
Reputation: 36965
This part:
return (
<div>
.. ???
</div>
);
is not ES6, it's JSX, an optional but useful addition to the React ecosystem. Unfortunately it requires an additional step to transpile the HTML-like syntax to JS.
Without JSX, but using ES6 and current version of React your code would look like this:
class NewGameButton extends React.Component {
render() {
return React.createElement( // universal createElement method
'div', // tag name as the first argument instead of React.DOM.div method
{
className: 'tic-tac-toe--new-game-button', // props as the second argument
onMouseUp: this.props.onClick
},
'New game' // children as the rest of arguments
);
}
};
Working demo: http://jsfiddle.net/69z2wepo/47252/
or the stateless function component approach:
const NewGameButton = props => React.createElement('div',{
className: 'tic-tac-toe--new-game-button',
onMouseUp: props.onClick },
'New game' );
http://jsfiddle.net/69z2wepo/47254/
If you were to use the JSX syntax (HTML-like code in JS) you'd need to add a transpilation step, and the React.createElement()
code above would be generated for you from this:
class NewGameButton extends React.Component {
render() {
<div className="tic-tac-toe--new-game-button" onClick={this.props.onClick}>
New game
</div>
}
};
or this:
const NewGameButton = props => (
<div className="tic-tac-toe--new-game-button" onClick={props.onClick}>
New game
</div>
);
Upvotes: 1
Reputation: 1844
May be that would help
class NewGameButton extends React.Component {
render() {
return (
<div className="tic-tac-toe--new-game-button" onMouseUp={this.props.onClick}>
New game
</div>
);
}
}
But i really suggest you to not use <div>
elements as clickable areas. Use <button>
instead, because it's more right for the semantic.
Upvotes: 0
Reputation: 5044
I would start off by going through the official React documentation https://facebook.github.io/react/docs/tutorial.html They give some good examples on how to get started and how everything should be structured.
Not sure what the end goal of your code is.... but any JSX markup can be returned in render.
So something like :
class NewGameButton extends React.Component {
render() {
return (
<div>
<input type="button" className="tic-tac-toe--new-game-button" onClick={this.props.onClick} />
<ChildComponent />
</div>
);
}
}
Upvotes: 0