A Live Developer Journal

React Components

Components are self-contained, reusable user interface building blocks that can be dropped onto any webpage. They each contain their own content (like a navigation menu with links), style (active page is looks different to other pages in the navigation menu, or show hide sub-menu items on hover etc) and behaviour (a progress bar that tells you how far down the page you are).

In React, we can define components in two ways:

By writing a JavaScript function

We can use a normal JavaScript function to define a component in React. Our function name starts with a capital letter, and is the name of our component. It accepts one argument, an object which stores all of the properties that the elements inside our components use (that we define using JSX syntax).

function Alert(props) {

Hello, {props.name}

; }

By writing an ES6 class

We can define a React component using an ES6 JavaScript class like this:

class Alert extends React.Component {
  render () {
    return <div>

Hello, {this.props.name}</p></div>; } }

In the example above, we have defined a class with the name of our component (Alert) which extends from the React.Component class, which turns our class into a component. The render method takes care of displaying the elements that make up our components (defined using JSX syntax) on the page. The properties that we access using this.props.name are available when we create a new instance of the component (not in the definition stage).