Functional Components

A React Component is an independent reusable chunk of code that outputs a React Element based on its properties and state.

There are two types of React Components:

In this section, we’ll focus on Functional Components.

I. Functional Components

Functional Components are functions that output React Elements. The first letter of the function name should be capitalized.

function HelloWorld(){
    return <h1>Hello World!</h1>
}

You can use the React Component in JSX by creating an HTML tag with the same name as the React Component:

const element = <HelloWorld/>

In brief, this example will render to a page as “Hello World”:

function HelloWorld(){
    return <h1>Hello World!</h1>
}

ReactDOM.render(
        <HelloWorld/>,
        document.getElementById("root")
    )

II. Adding Props to Functional Components

By using props, we can pass variables as information from one component to another component.

function HelloWorld(props){
    return <h1>Message: {props.message}</h1>
}

ReactDOM.render(
<HelloWorld message="Hello World!"/>,
document.getElementById("root")
)

Properties can be string literals, arrays or any other type of JavaScript object including other React Elements:

function HelloWorld(props){
    return <h1>Value: {props.numberArray[props.index]} </h1>
}

ReactDOM.render(
    <HelloWorld index = "3" numberArray={[1,2,3,4,5]}/>,
    document.getElementById("root")
)

You can supply as many property values as you want and they will all be accessible through the props argument.