JSX in React
Use JSX in React
JSX produces React “elements”
use curly braces to embed a JavaScript expression in an attribute
If a tag is empty, you may close it immediately with />
Adjacent JSX elements must be wrapped in an enclosing tag, such as div
Create Element
React elements are immutable. Once you create an element, you can’t change its children or attributes
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
Add Element
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id = "root"></div>
<script src="https://fb.me/react-0.14.3.js"></script>
<script src="https://fb.me/react-dom-0.14.3.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
<script src="script.js" type = "text/babel"></script>
</body>
</html>
//script.js
var Hello = React.createClass({
render: function(){
return (
<h2>Hello World!</h2>
);
}
});
ReactDOM.render(<Hello />, document.getElementById("root"));
Render Element
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));
}
setInterval(tick, 1000);