The first Component
32:00
create index.html. with some boilerplate (Brian uses emmet)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FrontendMasters React</title>
<link rel="stylesheet" href="/public/normalize.css">
<link rel="stylesheet" href="/public/style.css">
</head>
<body>
<div id="app">Text will be replaced once React mounts</div>
<script src="node_modules/react/dist/react.js"></script>
<!-- also need react dom for html -->
<script src="node_modules/react-dom/dist/react-dom.js"></script>
</body>
</html>
React will mount itself to #app. Why 2 libraries?
The history is that people wanted to use React for mobile apps (React Native), so they extracted the "view" into a separate module. So React can target the html dom or other view renderers like mobile or VR.
Then add the first React component. Adds inside the above html
// in index.html
vap MyFirstComponent = React.createClass({
render: function () {
return (
React.DOM.div(null,
React.DOM.h1(null, "This is my first component")
)
)
}
})
You need a the ()
to return
multi-line statements. 38:20
The
null
is the attributes you pass to the element. like classnames etc. createClass
and createElement
.createClass lets you create a blueprint for a new type of component. So you could render
MyFirstComponent
15 times. createElement
create one instance, one element:ReactDOM.render(React.createElement(MyFirstComponent), document.getElementById('app')
So above
React.DOM.div
is just a helper method for React.createElement('div', null...
42:22
Opens in browser, works. This is how simple it can be.
- how come React.DOM is in React and not in react-dom?
These are just small helper methods that wrap
createElement
. They are so small that they left it in for compatibility. 45:00
Extracts these helper methods:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>svideo</title>
<link rel="stylesheet" href="public/normalize.css">
<link rel="stylesheet" href="public/style.css">
</head>
<body>
<div id="app"></div>
<script src="node_modules/react/dist/react.js"></script>
<script src="node_modules/react-dom/dist/react-dom.js"></script>
<!-- 1. ++++ extract the helpers -->
<script>
var div = React.DOM.div
var h1 = React.DOM.h1
var MyFirstComponent = (
div(null,
h1(null, 'This is my first component!')
)
)
ReactDOM.render(MyFirstComponent, document.getElementById('app'))
</script>
</body>
</html>
Components in React are nothing but functions.Everything is a function call.
The only method from React DOM above is the
render
call. (line #24)47:00
questions, notes...
49:00
You could write React without JSX, babel, etc., but he doesn't really recommend it. He only knows one company that writes React with vanilla JS.