Write a Custom Function Component in React with JSX

Chris Achard
InstructorChris Achard

Share this video with your friends

Send Tweet
Published a year ago
Updated 2 weeks ago

React components are functions that return JSX (which looks like HTML, but is actually a flavor of javascript).

Once you create a new function component that returns JSX, you can then use it from inside of another component by returning it like any other component.

Chris Achard: [0:00] To define our custom components, we can just write regular functions. We write a function, maybe call it Greeting(). Notice it starts with a capital letter. That's important for functions, by convention.

[0:10] We want to return from that some JSX, which is what this is called down here. JSX looks like HTML, but it's a version of JavaScript that's compiled by Babel before it goes to the browser.

[0:21] From here, we could return a <div>, for example, with an <h1> that says Hello. Inside of JSX, say we have a variable here called name, and it says React. To display that inside of JSX, we use curly braces. Inside the curly braces, we can put any JavaScript expression. Name, by itself, is an expression that will return React.

[0:44] To use this Greeting, we can come down to our app and we can use it like a regular tag. We can use <Greeting /> as a tag. It's a self-closing tag because it has no children. When we save this, we get "Hello, React!" with our custom component.

Laureline Paris
Laureline Paris
~ 6 months ago

Hello, I would have correct the first thing said: the convention bit regarding the capital letter. "Notice it starts with a capital letter, that's important for functions by convention" I would have said: this convention ( starting the name with a capital letter ) is not applied for all functions. Here, the capital letter is applied because this function is actually representing a component ( which is specified in React doc to be a convention ) , but also more than that : it is representing a factory function ( implicitly, React returns an extended React.Component if I'm not mistaken )