Components & Props, Oh My!

“Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.”

Components modularize both functionality and presentation in our code. In order to understand how powerful this is, consider just how intricate web applications can become. The difficulty in logically arranging, architecting, and programming these web applications increases with their size. Components are like little packages: they help us keep everything organized and predictable while abstracting the ‘boiler plate’ code. Each component contains a snippet of code that describes what it should render to the DOM. Enough of a description — let’s see some examples!

Step 1 — write the components

  • a new class, Article, is declared
  • the class extends React’s component class (which provides us with built in methods and attributes)
  • a render( ) method is defined, and what it should return is explicitly provided (in render( ), we tell React “Hey, when you want to put this component on the DOM, here is what it should become!”)

Step 2 — use the components

Now that we have these components written, all we need to do is make sure some other component is making use of them in its render method. Every React application has some top level component(s). Very often, this top level component is simply called App. Let’s assume just that for our example:

Making Components Dynamic

We will use the following components:

  • BlogContent — contains the content of the blog post
  • Comment — contains one user’s comment
  • BlogPost — the ‘top level’ React component, which is responsible for rendering both BlogContent and Comment

Passing Information

React allows us to pass units of information from a parent component down to a child component. We call these props, which we will dig more into in a later lesson. Let’s see how we can pass information from BlogPost down to its child BlogContent:

Expanding our Application

We still need a Comment component that we can use for each comment in a BlogPost. The Comment component would look something like:

  • are modular, reusable, and enable a ‘templating’ like functionality
  • help us organize our user interface’s logic and presentation
  • enable us to think about each piece in isolation, enabling us to apply structure to complex programs

Conclusion

Thank you so much for stopping by! Please checkout my online portfolio and feel free to connect with me on Linkedin!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store