Write a Custom Function Component in React with JSX

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years 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.