Step 8
Undo the changes we've made to App.js
and index.js
:
App.js
function App() {
return <div>Hello React!</div>;
}
export default App;
index.js
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
Notice we import the App
in index.js
(and we also use ES6 modules with import/export statements).
The separation between the App.js
and index.js
is symbolic!
The philosophy of React is to decouple the process of creating an app and rendering it. So you can make the app and then decide to render it on a server, native devices, or even a VR environment.
Notice how <App />
looks like an HTML element (with angle brackets and all!). This syntax indicates a React component.
A Component is a building block in React that is ultimately responsible for returning HTML to be rendered onto a page.
Just as you can compose functions or classes to create more complex solutions/models, you can compose simpler components to create more complex ones.
<App>
<Header />
<Search />
<Output>
<Phonetics />
<Definitions />
</Output>
<Footer/>
</App>
React builds up pieces of a UI using Components.
Components can be classes or functions. This is a function component:
function App() {
return <div>Hello React!</div>;
}
export default App;
Here is the same component as a class:
import React from "react";
class App extends React.Component {
render() {
return <div>Hello React!</div>
}
}
export default App;
Notice the class component is more verbose. It has a render
method that returns a react element. A class component allows us to declare state and benefit from inheritance. However, if you don't need those perks, go for function components. Prefer the simplicity of functions.
Aside: React now has "hooks" that allow you to bind state with a functional component. We will explore this feature in a future chapter.