close

Rapid UI with React and UIkit

go

If you haven’t heard of React in front-end development, it’s a framework from Facebook that has taken the front-end web community by storm. Unlike other frameworks, React concerns itself purely with the view layer, leaving you to decide how you wish to deal with the other layers.

Like CSS frameworks, while React itself is easy to learn and very easy to roll your own components, creating all the components you require for a whole app can be extremely time consuming, especially when you have tight deadlines. As they say “a good developer is a lazy developer” and that is where the React community jumps in with its vast resource of components. Take a look at the list of components on react parts. In most cases, there is no need to reinvent the wheel and you’re usually up and running in no time, giving you the time to focus on the other importants parts of your app.

 

So what is React UIkit Components?

I’m a huge fan of the UIkit CSS framework for developing fast and powerful web interfaces and I really wanted to use it with React, using the css and using React to handle the functionally. I won't go into the arguments for CSS or inline styles in React, as both have their advantages, and it really depends on the project you’re building as to which way to go. If you are building a web only interface then CSS is more than sufficient, even though either will do.

When I first started learning React, there weren’t that many React CSS libraries and none that used UIKit. As I was developing my app and building my components I was constantly refactoring my components and noticed that many components shared the same functionality or they were nested inside other layout components. So I decided to address the components creation issue  as a whole, which React makes easy.

Essentially what I wanted was;

  • Modular components
  • Only have the components that are used in the app as a dependency
  • Create multiple elements from a single component
  • Apply UIkit classes via props
  • Have an easy way to extend and create new custom components with all the beauty of UIkit
  • Predictable, tested components
  • Port components in a way that is more suited for React.

The last point, was to not simply port a single components for every component in UIKit, as the two projects come from slightly different angles. As React UIkit Components wraps both the functionality and structure into a single module component some things have been moved around. For example, there is no cover component, but rather the responsive cover class has been moved into the image component. And that is how React UIkit Components were born.

React UIkit Components is a collection of module components which allows you to write less code and put interfaces together fast for both prototyping and production, leaving you to concentrate on the logic and styling of your app.

screen_shot_2016-08-15_at_16.00.01.png

 

There are currently 29 main components which contain many sub components and elements via the components props. E.g FormInput can create one of 11 different sub components by changing its prop attributes.

Alert, Article, Badge, Base, Block, Button, Button Group, Codeblock, Comment, Comment List, Dropdown, Flex, Form, Grid, Icons, Img, Img Gallery, List, Modal, Nav, Note, Overlay, Placeholder, Panel, Table, Text, Thumbnail, Trigger

 

JSON orientated components

React UIKit Components takes a JSON first approach, whereby many of the components will take an items or body prop in addition to the children prop allowing JSON data straight from an api or service to be injected into the component creating all its sub components.

screen_shot_2016-08-15_at_17.14.26.png

 

It’s all about the base

At the heart of React UIkit is the base, which is a higher order component that wraps around all the other components and facilitates the creation of new components which absorbs all the utility classes including float, border radius, alignment, margin and responsive width. Along with Ulkit classes, the base component comes with convenient helper functions for media, screen, breakpoints and cleaning classes and props.

Creating a React UIkit Component is really simple. Pass a component to the base function.

// code - component.js
import React from 'react';
Import uikit = 'react-uikit-base';

const Component = (props) => {
  const cssClassNames = helpers.cleanClasses([
    props.classes,
    props.className
  ]);

  const cleanProps = helpers.cleanProps([])(props);

  return <div
    className={cssClassNames}
    {...cleanProps}
  >
    {props.children}
  </div>;
};

export default uikit.base(Component);

 

Subscribe form example

In this example we will create a subscribe to a new letter form component. We will also use the create-react-app from Facebook so we don’t have to configure any of the tooling.

screen_shot_2016-08-17_at_17.58.24.png

 

Installation

Node.js 4.x or higher is required.

Note: create-react-app requires that eslint and any eslint plugins are installed globally.

Open your terminal and install create-react-app.

$ npm install -g create-react-app
$ create-react-app subscribe && subscribe

 

Once installed you should see something like the following:

screen_shot_2016-08-15_at_18.54.18.png

 

You will also need to install some peer dependencies for react-uikit-components

$ npm install --save-dev cuid ufunc react-uikit-base react-uikit-overlay react-uikit-img react-uikit-button react-uikit-form react-uikit-grid react-uikit-icon

 

A quick run down on the peer dependencies:

  • cuid is a short random string with some collision-busting measures for creating ids
  • ufunc is a set of  functions for functional programming
  • react-uikit-base is the base component which creates all other components
  • react-uikit-overlay is a component for creating image overlays
  • react-uikit-img is a component for responsive images
  • react-uikit-button is a component for creating various buttons with many variations
  • react-uikit-form is a component for creating forms and form elements
  • react-uikit-grid helps with component layouts
  • react-uikit-icons for easily adding icons

react-uikit-overlay, react-uikit-button and react-uikit-form make up the main parts of the form along with an input and grid.

As a lot of the react-uikit-components share the same dependencies, the modules (or a different version) might already be installed. Therefore they are not automatically installed as dependencies. More information on peer dependencies can be found on the node website.

Finally start the server

$ npm start

screen_shot_2016-08-15_at_19.22.53.png

 

Building the component

Now we will open the subscribe project in our editor and get coding.

As react-uikit-components does not include the UIKit CSS framework it must be added to the project manually. There are many ways to add UIKit’s CSS but we will use a CDN and add it to the index.html.

<!-- code - index.html -->
!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>React App</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.26.4/css/uikit.min.css">
  </head>
  <body>
    ...

 

Create a subscribe.js file inside of  the src directory. In the subscribe.js file import react and the five components that will make up the subscribe form

// code - src/subscribe.js
import React from 'react';
import Button from 'react-uikit-button';
import Grid from 'react-uikit-grid';
import Overlay from 'react-uikit-overlay';
import Form from 'react-uikit-form/';
import FormInput from 'react-uikit-form/lib/form-input';

 

Next we will add the Subscribe component. So that the Subscription component can be reusable as well as be externally executed, it will be a stateless, dumb component which will only receive props but not set any state internally or externally.

code - src/subscribe.js
import React from 'react';
...
const Subscribe = (props) => (
  <Grid>
    <Form
      colSmall='4-5'
      colMedium='2-5'
      center
    >
    </Form>
  </Grid>
);

export default Subscribe;

 

Inside the Subscribe component is a Grid component, which creates a grid of children components.

Form is the only component but to stop it from stretching the full width of the screen col props are added, which state how many columns a component should span. Every component includes its own col props so there is no need for extra columns or row containers for layout. There are also responsive cols which can be used dependent on the screen width, like the ones we just used. colSmall creates a width of 80% of the grid if the viewport is more than 479px and colMedium creates a width of 33.33% if the viewport is more than 767px. The center prop centres the form horizontally.

Inside of the Form we’ll add an Overlay component, which is a container with an image as the background covered by a transparent color. Overlays allow placing of components or any HTML element on top of the Overlay which we can use to display our message.

Add an Overlay inside the Form component

// code - src/subscribe.js
<Form
 ... 
>
  <Overlay
    background
    src='./subscribe.jpg'
  >
    <h2>{`Stop! {KOLAB}orate and listen!`}</h2>
    <p>Sign up to are great newsletter for all kinds of awesome things, suff.</p>
  </Overlay>
</Form>

 

The Stop! {KOLAB}orate and listen! text is placed inside of template literals to escape the curly braces.

While this looks okay it would look better if the text was centred. There are other ways to achieve this but this is an opportunity to use element from react-uikit-base. Element is a built in element that returns a div with all the functionality of the base component.

Add a new import for the element and add a Centered component. Now wrap the Overlay heading and paragraph inside of the Centered component.

//code - src/subscribe.js
import React from 'react';
... 
import { element } from 'react-uikit-base';

const Centered = element();

const Subscribe = (props) => (
  ...
      <Overlay
        background
        src='./subscribe.jpg'
      >
        <Centered vertical='middle' tall='parent'>
          <h2>{`Stop! {KOLAB}orate and listen!`}</h2>
          <p>Sign up to are great newsletter for all kinds of awesome things, suff.</p>
        </Centered>

      </Overlay>

 

The vertical prop adds UIKits vertical alignment classes to the Centered component. The tall prop sets the height to 100%. As the vertical prop creates an outer container we need that container to be 100% (not the element itself) and that is what tall=’parent’ is doing.

So that's the Overlay component complete and time to move on to the form.

The form is very simple and consists of only an input with an icon and sign up button, which stretch the full width of the overlay.

Again we will also add a grid for layout and a gutter collapse prop so there will be no gap between the input and the button.

//code - src/subscribe.js
  </Overlay>

   <Grid gutter='collapse'>
        <FormInput
          colSmall='3-5'
          wide
          icon='envelope'
          placeholder='Enter Your Email'
          onChange={props.onChange}
        />
        <Button
          colSmall='2-5'
          body='Sign Up'
          onClick={props.onSubmit}
        />
    </Grid>
</Form>

 

Quick breakdown of the two new components props.

FormInput props:

  • colSmall - adds a width of 60% once the viewport is more that 479px.
  • wide - adds a width of 100%.
  • icon - places an icon inside of the import form.
  • placeholder - adds placeholder text for the input.
  • onChange - event which will be handled by an function passed to the onChange prop that fires everytime the input changes.

Button props:

  • colSmall - adds a width of 40% once the viewport is more that 479px.
  • body - used for the content of the button. Alternatively this could be added inside between the Button tags.
  • onClick -  event which will be handled by an function passed to the onChange prop that fires everytime the input changes.

As we now have props, we need to add these to the propTypes below our Subscribe component

//code - src/subscribe.js
...
const Subscribe = (props) => (
  <Grid>
    <Form
      colSmall='4-5'
      colMedium='2-5'
      center
    >
      <Overlay
        background
        src='./subscribe.jpg'
      >
        <Centered vertical='middle' tall='parent'>
          <h2>{`Stop! {KOLAB}orate and listen!`}</h2>
          <p>Sign up to are great newsletter for all kinds of awesome things, suff.</p>
        </Centered>
      </Overlay>

      <Grid gutter='collapse'>
        <FormInput
          colSmall='3-5'
          wide
          icon='envelope'
          placeholder='Enter Your Email'
          onChange={props.onChange}
        />
        
        <Button
          colSmall='2-5'
          body='Sign Up'
          onClick={props.onSubmit}
        />
      </Grid>
    </Form>
  </Grid>
);


Subscribe.propTypes = {
  onChange   : React.PropTypes.func,
  onSubmit  : React.PropTypes.func
};

export default Subscribe;

 

Open the App.js file and added the Subscribe component

//code - src/App.js 
…
import Subscribe from './subscribe';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img
            src={logo}
            className="App-logo" alt="logo"
          />
          <h2>Welcome to React</h2>
        </div>
        <Subscribe
          onSubmit={this.onHandleSubmit}
          onChange={this.onHandleChange}
          />
      </div>
    );
  }
}

 

You may have notice that the onHandleChange and onHandleSubmit methods in the Subscribe props don’t exist. We’ll add them next as well as some state to test the component.

A word on state. It is not advisable to keep state inside of components. While convenient, as your app's requirements change other parts of your application might need to share or know the state which it cannot access as it has been concealed inside of the component. It is recommend to handle state externally using something like Redux and passing the state to the component via its props. Only for the purpose of this example the state will be added to the App component.

As App.js is an es6 class both the onHandleChange and onHandleSubmit methods will need to be bound in its constructor to be able to access it in the render method. This is also the place where the state will be added.

//code - src/App.js 
...
class App extends Component {
  constructor (props) {
    super(props);

    this.state = { email: '' };

    this.onHandleChange = this.onHandleChange.bind(this);
    this.onHandleSubmit = this.onHandleSubmit.bind(this);
  }

  onHandleChange (e) {
    this.setState({ email: e.target.value });
  }

  onHandleSubmit (e) {
    alert(this.state.email);
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img
            src={logo}
            className="App-logo" alt="logo"
          />
          <h2>Welcome to React</h2>
        </div>
        <Subscribe
          onSubmit={this.onHandleSubmit}
          onChange={this.onHandleChange}
          />
      </div>
    );
  }
}

 

  • onHandleChange method sets the email state to the value of the input element.
  • onHandleSubmit shows an alert with the value of email state when the button is clicked.

The subscribe example can be downloaded at https://github.com/otissv/react-uikit-subscribe-example

 

What's next ?

There’s still lot of components from UIkit to come as the goal is port to React as many components as possible. A starter kit to build components will also be released shortly. Also another feature I am keen to add (starting with the base component) is support for inline styles using the same interface.

Full documentation on all the components can be found at React UIkit Components. The docs are currently being updated to version 2 but the api is mostly the same.

If you would like to contribute you can send a pull request or feel free to contact me.

 

Email: otissv@gmail.com

Twitter : https://twitter.com/otissv

Github https://github.com/otissv

 

Resources

React UIkit components

UIkit

Alert

Article

Badge

Base

Block

Button

Button Group

Codeblock

Comment

Comment List

Dropdown

Flex

Form

Grid

Icons

Img

Img Gallery

List

Modal

Nav

Note

Overlay

Placeholder

Panel

Table

Text

Thumbnail

Trigger

Create-react-app

Redux

Author:

screen_shot_2016-08-19_at_12.41.06
Otis
  • react
  • UIkit
  • tutorial
  • guide

Get in Touch