Getting started with React Cosmos

Written by Elizabeth Amaechi ✏️

Introduction

One of the many selling points of React is that users can build components and reuse them repeatedly within a specific codebase. You can take this feature further with the help of the React Cosmos developer tool.

React Cosmos is used for building isolated and scalable React components. It lets you create a sole component for your React application. You can consider different use cases as well as different design patterns when making use of React Cosmos, which will allow you to create very versatile, isolated components that fit many other conditions.

Benefits of using React Cosmos

React Cosmos works by making use of component features. The sum of these component features is what makes up your component library. This is then rendered on a UI for easy tracking. A major benefit of using React Cosmos is that it can scan any of your React projects and let you render the components within each of them, with any combination of props or in any state.

In this section, we’ll go over some of the many benefits of using React Cosmos.

Reusable component creation

As stated earlier, React Cosmos takes the reusability benefits of React to the next level, allowing for the creation of isolated and reusable components. This gives you more room to create a robust architecture while preventing you from having to rewrite an already defined UI.

UI sharing across different projects

In addition to reusing a UI within a given project, React Cosmos allows for the reusability of a component across various projects in your portfolio. This is really helpful in creating solid and uniform branding across your project.

Easy debugging

It is much easier to identify and fix errors in your application when you use React Cosmos because it isolates components into individual units, rather than forces you to work with non-isolated components. This makes development much easier and faster because it’s much easier to figure out your error sources.

Build and publish your component library

You can make any of your React Cosmos components publicly available for your coworkers or anyone on the internet. This can come in handy should you decide to build or launch your own component library for public use.

Real-time external API mocking

Users can see the current state of their application in real-time by mocking external APIs. This makes development faster and can also come in handy during debugging.

Installing React Cosmos

React Cosmos can be used on any React or React Native project, but for this article, we will focus on React. Make sure that you’ve installed your React project beforehand with the use of npx create-react-app.

Now, let’s install React Cosmos in our React project using either npm (Node Package Manager):

npm i --D react-cosmos

or Yarn:

yarn add --dev react-cosmos

You can confirm that installation is successful by checking the package.json file in your React project.

After installation, the next step is to create a package.json script in your application. This will enable you to start your Cosmos project. Include the following code under the script section of your package.json file:

"scripts": {
      "cosmos": "cosmos",
      "cosmos:export": "cosmos-export"
}

Your whole package.json file should look as so:

{
"name": "reactcosmos",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "cosmos": "cosmos",
    "cosmos:export" : "cosmos-export"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "react-cosmos": "^5.6.2"
  }
}

Let’s proceed to start our application.

Launching our React app with React Cosmos

Run the below command within your terminal:

Using npm:

npm run cosmos

Or, using Yarn:

yarn cosmos

You should be prompted to visit localhost:5000 to view your component libraries. You won’t see any components there yet because we haven‘t built any.

If you’re faced with an error message, you should do the following:

  1. Create a file called babel.config.js and update its content with the code below:
module.exports = {
       presets: [
          ['@babel/preset-env', {targets: {node: 'current'}}],
          ['@babel/preset-react', {targets: {node: 'current'}}] // add this
       ]
    };
  1. Create another file called postcss.config.js and update its content as so:
module.exports = {}

This should fix any Babel or PostCSS issues. If the error persists, then you can read through the message and try to troubleshoot or browse the error message on your favorite browser.

Building our first React component

To build our first component, we need to create a fixture. Fixture files usually contain only one default export — either a React component or a React node. To create one, we need to add .fixture to the name of the file containing our component — we’ll use main.fixture.js. This way, React Cosmos can easily track it.

Proceed to create a file named button.fixture.jsx within the src folder of your React application. The next step is to update the file with the code below:

// button.fixture.jsx
import React from 'react';

export default function Hello() {
  return <h1>Hello, World</h1>
}

Hurray! You just created your first isolated component using React Cosmos. To confirm this, proceed to localhost:5000 again, where you should see your first component listed under All Fixtures.

Updating your React components

Now that we have successfully created our first component, we can proceed to update it. In this section, we’ll build a button component. Proceed to update the content of our button.fixture.jsx file as shown below.

import React from 'react';
import './button.fixture.css'

export default function Button() {

  return <button> Hey, Click me</button>;
}

What we did above is create a button tag and linked our yet-to-be-created CSS stylesheet. Now, create another file called button.fixture.css for our button component styling. Update the content of the new file as follows:

button{
    padding:10px 20px;
    color:#fff;
    border:none;
    outline:none;
    background-color: teal;
    border-radius: 8px;
    display:block;
    margin:auto;
    margin-top:40px;
    cursor:pointer;
}

This will style the newly-created button. You can once again proceed to localhost:5000 to see the changes we made to our component.

We have successfully created and updated our isolated button component! It can now be used for our different applications. As you create more components, they will show up within your pre-rendered dashboard for viewing.

Note that fixture files must be located within the src folder of your React application. You can create a fixture either by adding .fixture to your filename or creating a __fixtures__ folder and placing all your fixture files within it.

Multi-fixture files

It can be challenging to export more than one component from a single fixture file, especially when you allow for just one default export. You can walk around this issue by placing your components in the form of an object, as shown below; this will enable you to export multiple components with one fixture file.

export default {
  primary: <PrimaryButton>Click me</PrimaryButton>,
  primaryDisabled: <PrimaryButton disabled>Click me</PrimaryButton>,
  secondary: <SecondaryButton>Click me</SecondaryButton>,
  secondaryDisabled: <SecondaryButton disabled>Click me</SecondaryButton>,
};

Conclusion

React Cosmos is an excellent way to create an isolated component for your current or future React application, particularly as it comes easy-to-use and with swift debugging, among other benefits. Try out React Cosmos for easy and faster development the next time you’re building components!

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — start monitoring for free.

25