DEV Community

bellagerken
bellagerken

Posted on

What I learned about React Components

When learning Javascript for the first time, all of our code to render information on a webpage was on one index.js file. While this is convenient for a small website, as more complex websites are built with lots of different pieces, it can be difficult to keep your code organized.

React introduces a way to organize your data in a way that will allow the programmer to render independent and reusable pieces to the DOM. Components contribute to the functionality and presentation of our code, which becomes more and more helpful as our web applications become more complex. The simple goal of a React component is to contain a smaller section of code that describes what should be rendered to the
DOM.

In order to write a component, we must declare a function and name it starting with a capital letter. The capital letter differentiates javascript functions from react components, and must be used in order to render the components to the DOM. The return value for the function contains a snippet of JSX. The beauty of a React component is that if we then wanted to render this JSX multiple times, we could repeatedly call on this component so that is gets rendered with no variations. It is almost as if components are like functions for rendering sections of JSX to the DOM.

An example of a component that would create a header tag is:

function Header(){
  return(
    <div>
      <h1>Hello</h1>
    </div>
  )
}

export default Header
Enter fullscreen mode Exit fullscreen mode

When finished writing a component, we export it and import it to its parent component in which it will use in its return statement. It is common of react applications to contain one main component, typically called App.js, that renders the application's top-level components.

An example of how a our Header component would be imported and returned in its parent (App) component is detailed below:

import Header from "./Header"

function App(){
  return(
    <div>
      <Header/>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

What this translates to is:

function App(){
  return(
    <div>
      Hello
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Overall, React components make a programmer's life much easier by organizing their code in a way that renders JSX through small sections of code that are independent, and reusable.

Top comments (0)