Functional React Components and Props

In this post, I’ll show how to build an avatar using functional React components. You can think of React components as isolated building blocks to reuse throughout an application. They accept inputs and return elements for updating the DOM.

Functional React components are pure. Just like pure functions in JavaScript their execution doesn’t depend on the state of the application, they don’t modify any variables outside their scope (no side effects!), and they always return the same result given the same arguments. Because of React’s adherence to pure components, learning React makes you a better developer. It also makes testing easier.

To start our avatar component, let’s think about what building blocks we’ll need to make it. An avatar has a user image, a user name and a probably a link to a user profile. Hmm, sounds like we need a user object. We’ll define one using an ES6 constant, call ReactDOM’s render method and pass it our forthcoming Avatar component.

ReactDOM’s render method takes two arguments — our avatar component that returns a UI object and the element in the DOM where the UI will be updated to. As we “invoke” the Avatar component we pass it the user as props, essentially parameters the component will use to create the UI. Now we can define an Avatar function and access the user object.

Our Avatar component is comprised of three other components: ProfilePic, ProfileName and ProfileLink. Each needs access to some part of our user object. As we “invoke” the child components, we pass in the necessary props. It’s important to note that the React component rendered in the DOM must be wrapped in a div.

With our child components we don’t need to worry about a container. Each child component can just return whatever element it needs to. And that’s pretty much all there is to building function react components. Nothing too fancy — it’s very similar to writing pure functions with JavaScript. The only difference is we’re returning JSX instead of primitive values.

Checkout the example on CodePen.