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.
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.