Writing a Function Component
Learn about the basics of React components and create dynamic navigation components.
React components and dynamic HTML rendering
The function, representing a component, defines what to update on the screen. It returns a value composed of some HTML-like code. We must be quite familiar with elements such as <ul>
and <li>
; React also allows the addition of JavaScript expressions within these elements. When used together, it requires the JavaScript expression to be wrapped in a pair of brackets, {}
. The job of this expression is to provide dynamic HTML content.
For instance, if we have a text variable and would like to display it, we could do the following:
// Title component with static contentconst Title = () => {const text = "Hello World1";return <h1>{text}</h1>;}
Or, if the text is returned from a function, we can do the following:
const Title = () => {// Function fn returning "Hello World"const fn = () => "Hello World";// Render an h1 element with the result of invoking the functionreturn <h1>{fn()}</h1>;}
We know that this JavaScript expression is filled in the location where the children
prop is. The children element does not have to be a single element; it can be an array of elements as well:
const Title = () => {// Array 'arr' containing elements 'Apple' and 'Orange'const arr = ['Apple', 'Orange'];// Render an unordered list with list items for each element in the arrayreturn (<ul>{arr.map((v, index) => (// Each list item corresponds to an element in the array<li key={index}>{v}</li>))}</ul>);}
It seems a bit complicated in the above code, so let’s first look at the result to understand what the code tries to achieve:
// Render an unordered list with specific list items (Apple and Orange)// Note: Using an array to directly include JSX elements in the listreturn (<ul>{[<li>Apple</li>, <li>Orange</li>]}</ul>);
Basically, it wants to output two li
elements. To get there, we create an array containing two elements with a JavaScript expression. Once it becomes a JavaScript expression wrapped in brackets, {}
, anything in JavaScript can be refactored and programmed however we want. We can use
Get hands-on with 1400+ tech skills courses.