3.1: Calling Functional Components
A Functional Component is essentially a function, so like a function, we need to call the function to use it. Most of the time, when you call an instance of a component, it will be called similarly to an HTML self-closing tag, and the call should generally be the same name as the component itself. So for instance, this component is called FunctionalComponentDemo, so we'll call it like this
<FunctionalComponentDemo />
Where to call it?
Let's play around a little bit so that you can see how to call a component.
Go to
App.js
.Add an import for the Functional Component file.
Remove the items inside the tags currently inside the div tag.
Add the call of the component
<FunctionalComponentDemo />
.
One more quick change: 1. Go to App.css
. 2. Change the text color to red: color: red
. 3. You can remove the background-color: white;
rule, if you have it.
Run npm start
. You should see the following:
Quick Explanation
So what's happening here? 1. We have the FunctionalComponentDemo Component. 2. Which is being called in App.js
. 3. App.js
is being called inside of index.js
. 4. index.js
has a ReactDOM.render() method where <App />
is passed in as a parameter. 4. index.js
is reaching out to the root in the index.html
file where it is being rendered.
Notice how there is a sort of flow to the data here. It goes through a channel where it eventually finds the HTML. The FCDemo Component is a child of the App Component. The App Component is a child of index, and index is the main parent Component. This unidirectional flow is what people love about React.
Rule: Data flows in one direction in React.
When you run the app, we want it to look like this:
Unfortunately during our demo we removed some code from App.js
. Let's take the app back to where it was. You'll need to change the App.js
file and the App.css
file back by hitting ctrl + z
. It should do it even if you have saved, unless the file has been closed since it was last edited. If not, here is the App.js
for your convenience:
and here is part of the App.css
file:
Sidedbar.js
With our current routing, to get the Component firing properly we need to call the Components in our Sidebar.js
file where we're doing all of our routes. Note the plusses to see what we've added.
Notice that we're adding it as an import. Then, we're also adding a path, /functionalcomponent
. When we go to that path it will fire the Component.
Styling
Let's add some classes that we already made in App.css
for simple styling in the Functional Component. In your FunctionalComponentDemo.js, add the className
attributes and string values.
At this point when you click on the "Functional Component" link in the sidebar, your app should look like this:
Let's take a look at the next module.
Last updated