Components in React

Author
By Darío Rivera
Posted On in React

Components are reusable UI building blocks that encapsulate markup (HTML), style (CSS), and logic (JavaScript) into reusable elements. In React, everything is a component: buttons, forms, layouts, and even entire pages. Let's take a look at this core concept. 

The simplest way to define a component in modern React is with a JavaScript function:

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

This is called a function component. The function name MUST start with a capital letter and return JSX, which is a syntax extension for JavaScript that allows you to write HTML-like code directly inside your JavaScript files.

To use a component, you include it as a JSX tag:

function App() {
  return (
    <div>
      <Hello />
    </div>
  );
}

You can also pass data between React components using props.

Passing props to a component

Props are inputs to a React component. They are passed from a parent component to a child component, similar to function arguments. In React, components are just functions, and props are just parameters.

Let's take a look at the following component. It returns a JSX with a salutation text inside a paragraph. Observe how the name prop is being passed from the function signature to the JSX. This syntax is called destructuring.

function Greeting({ name }) {
  return <p>Hello {name}</p>
}

The prop can be passed using an HTML-like syntax as follows.

function App() {
  return <Greeting name="John Doe" />
}

Let's take a look at this example in CodePen.

See the Pen Passing props to child elements in React by Darío Rivera (@fermius) on CodePen.



Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.