3.0: Functional Components Overview
Hopefully, you noticed that we have separate files for Header, Footer, Sidebar, and Resources. These are all known as components in React. Components are individual pieces of the User Interface that can be altered independently of one another.
There are two types of components: "Functional Components" and "Class Components". In this project, we'll start by talking about and working with "Functional Components".
Functional Components
Functional components have the following capabilities/traits:
Rendering of information without using or changing state.
Known as presentational components.
Often used for simple chunks of code.
No 'this' keyword. Class components use 'this' extensively.
Known as dumb components.
Often used as child components that will receive 'props' (aka properties) from a Class Component (parent).
Directory Setup
In the components folder set up a concepts folder and a FunctionalComponentDemo.js
file:
Rule: Component names must be capitalized, and they generally are Pascal cased. This means that all separate words have capital letters.
Functional Component Example
Let's create a simple functional component in the FunctionalComponentDemo.js
file. At this point you probably want to start typing (instead of copying and pasting) so that you can get a good feel for the React keystrokes and syntax. Add the following:
You should see an error at this point. Why? If you hover over the error, it should say Expression expected
. Because a functional component is a function that should return something. Let's do that:
Here we added a few lines that appear to be a simple bit of HTML. However, they are actually something called JSX, which we'll talk about in a future module. For now, assume that it's working just like HTML.
For the component to work, we need to export it. See the bottom line:
We now have a component that can be used in our application that will render to the dom.
Run the app. Does it work? It shouldn't have any change at this point. Why is this? Well, we need to call the component. Let's discuss that next.
Last updated