DEV Community

Cover image for Extracting React Components
savannaac
savannaac

Posted on

Extracting React Components

And React for the home stretch. After struggling with vanilla JavaScript, a language seemingly bound by few rules, learning React was almost comforting. In React, there's structure and how data flows is clearly defined. With a myriad of chat apps, from Facebook to Slack, I thought: Why not add another one to the mix?

Why React

Despite succumbing to many hard rules, React is efficient and flexible. Code is broken up into small, isolated pieces, which make up components. These components interact and communicate with each other, building complex UIs.

Components

Components are independent, reusable bits of code. Together, they make up an app. They take in parameters called props and display views through a render() method.

While building my chat app, I was initially writing big, complicated components while trying to get the flow of things. The render() method returned long descriptions, full of JSX, which goes against the core concepts of React. My code was neither independent nor flexible.

oh no reaction

Cleaning Up the Code

In all of my components, I noticed I had copied and pasted code for a header over and over again, so it made sense to refactor that code into its own lil' component.

There are two types of components: functional components and class components. To define a component is as easy as writing a function:

code snippet of react functional component

I assigned an arrow function to a variable Header. The function returns an element, which is a description of what I want my header to look like and that's fancy text - still text but fancy. I wrapped my <h3> tags in a <div> because React components can only return a single element.

And there it is - a super simple and easy lil' functional React component.

Then, I export it to be used somewhere else.

Rendering a Component

Next, to render it in another class component, I import it at the top.

import {function} + relative file path

Using JSX, I can basically place the code wherever I want and as many times as I want in the render() method.

code snippet of rendering react functional component in class component

Those same steps can be applied to other pieces of code, especially HTML elements, creating code that is flexible, efficient, and easy to read.

Top comments (0)