DEV Community

Cover image for Build Beautiful Websites Fast With Semantic UI And React
Grégory D'Angelo for AlterClass

Posted on • Originally published at alterclass.io

Build Beautiful Websites Fast With Semantic UI And React

Table of Contents

  • Add Semantic UI to a React with Semantic UI React
  • Use Semantic UI React Components
  • Build Authentication Pages with Semantic UI React
  • Conclusion

Add Semantic UI to a React App with Semantic UI React

Semantic UI is an open-source framework used to build User Interfaces. It provides a set of UI components and flexible theming support that helps to build web applications. In other words, Semantic UI makes our life easier as we do not have to create components from scratch every time we build web applications. We just need to compose our UI using pre-defined components from the Semantic UI framework and customize them as we like.

However, Semantic UI uses jQuery to manipulate the DOM. But as you know, the whole point of using React to build your web application is its declarative nature. To put it simply, there is no point in having jQuery alongside React. React is handling the DOM manipulation for us. So, jQuery is simply not compatible and useless when working with React.

But wait! How do I use Semantic UI components in my React application?

Thankfully, Semantic UI provides integration with React through Semantic UI React. This library provides a React implementation of the original Semantic UI framework. It is jQuery-free and declarative. Just what we wanted.

The best way to integrate Semantic UI to our React application is by installing Semantic UI React package via npm or yarn:

yarn add semantic-ui-react
// or
npm install semantic-ui-react
Enter fullscreen mode Exit fullscreen mode

This package provides us with the React version of the Semantic UI components.

Semantic UI React also needs a Semantic UI theme to style the React components properly. It is provided by Semantic UI from the Semantic UI CSS package. This package provides a lightweight CSS only version of Semantic UI, and can be installed via npm or yarn:

yarn add semantic-ui-css
// or
npm install semantic-ui-css
Enter fullscreen mode Exit fullscreen mode

Then, we can import the stylesheets in our React application from the entry point file:

import React from 'react';
import ReactDOM from 'react-dom';
import 'semantic-ui-css/semantic.min.css';

import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

We are all set! Semantic UI can now be used anywhere in our React application.

In the next section, I will show you how you can import, use, and compose, the pre-built components provided by Semantic UI React to speed up your development process.

Use Semantic UI React Components

Import and Declare Semantic UI React Components

Semantic UI React provides out of the box components that we can import and render in our React application. Those components are ready to use and highly customizable through props and composition.

If I want to add a button to my application, I can simply import it from Semantic UI React and declare it using JSX:

import React from 'react';
import { Button } from 'semantic-ui-react';

export default function App() {
  return <Button>Click me</Button>;
};
Enter fullscreen mode Exit fullscreen mode

The main advantage of using the Semantic UI React Button component, is that it comes with a bunch of props and sub-components you can use to configure it and style it as you want. It saves you HOURS of development as you don't have to build your own button from scratch.

Here's how you can easily add a loading Button into your App using Semantic UI React:

import React, { useState } from 'react';
import { Button, Icon } from 'semantic-ui-react';

export default function App() {
  const [loading, setLoading] = useState(false);

  const save = async () => {
    setLoading(true);
    // some async operation here
    // await ...
    setLoading(false);
  };

  return (
    <Button
      size="large"
      color="blue"
      type="submit"
      loading={loading}
      onClick={save}
    >
      <Icon name="save" />
      Save
    </Button>
  );
};
Enter fullscreen mode Exit fullscreen mode

Compose Semantic UI React Components with Custom Element Type

Each Semantic UI React component, such as the Button, has a set of pre-defined props you can use to configure and style it. You can find a list of all the props supported by a component in the online documentation.

Besides from that, each Semantic UI React component has a special prop called as. This prop provides a way to render a custom element type for any component. One typical example is when we want to use a Button component and benefit from its pre-defined features, but render an a HTML tag instead of a button HTML tag.

<Button as="a">Click me</Button>
Enter fullscreen mode Exit fullscreen mode

It allows composing component features and props without adding extra nested components.

Like the Button, each Semantic UI React component has a default value for the as prop.

Compose Semantic UI React Components with 3rd Party Libraries

Another great advantage of Semantic UI React is its ability to pass all unhandled props and DOM attributes down to the components.
This is valid for all Semantic UI React components. So, like in our example above, type is an unhandled prop on Button and will be passed through.

Combined with the as prop, this feature allows composing with third-party libraries like the popular react-router.

In the following example, we can use the Semantic UI React Button component, render it as a Link component from react-router, and pass the to prop required by Link.

import React from 'react';
import { Link } from 'react-router-dom'
import { Button } from 'semantic-ui-react'

<Button as="Link" to="/home">Home</Button>
Enter fullscreen mode Exit fullscreen mode

Leverage Shorthand Props

Some Semantic UI React components, such as the Button, can have shorthands. Those shorthands are pre-defined props that allow to configure the content of a component. In other words, you can declare and customize the children of a component using props only. It saves you writing extra JSX tags.

For example, Button has a content shorthand for its primary content.

<Button content="Save" />
// is equivalent to
<Button>
  Save
</Button>
Enter fullscreen mode Exit fullscreen mode

It also has an icon shorthand, to add an Icon Semantic UI React component to its children.

<Button icon="save" content="Save" />
// is equivalent to
<Button>
  <Icon name="save" />
  Save
</Button>
Enter fullscreen mode Exit fullscreen mode

What's even more powerful about those shorthands is the ability to customize the default element rendered by the shorthand using an object or a function as the shorthand value 🤯.

Let's see it in action with our Button example:

<Button 
  content="Like"
  icon={{ color: "red", name: "like" }}
/>
// is equivalent to
<Button
  content="Like"
  icon={(Component, componentProps) => <Component {...componentProps} color="red" name="like" />}
/>
// is equivalent to
<Button>
  <Icon color="red" name="like" />
  Like
</Button>
Enter fullscreen mode Exit fullscreen mode

Function value as the shorthand is very useful when you want to render a custom element in place of the shorthand element. Like in the following example, instead of rendering an Icon, we are returning the Label Semantic UI React component (with its own props) from the icon shorthand:

<Button content="Like" icon={(Component, componentProps) => <Label basic>+1</Label>} />
Enter fullscreen mode Exit fullscreen mode

Controlled/Uncontrolled Components

One more thing before we dive into a more practical example. Semantic UI React components maintain their own state internally and update it based on user input. They are what React called controlled components. This behavior is provided by Semantic UI React out of the box. Semantic UI React is built to make your life easier!

So, for example, if you have a Semantic UI React Dropdown component, you do not have to worry about managing the open/close state of the dropdown when the user clicks on it. The onClick event and the open state are handled by default inside the Dropdown component. The same thing happens with other events like onChange and the value state.

But in some cases, you still need to take control of some of the component states and events yourself. This is totally feasible. You just need to define the corresponding prop, and the components will delegate control for that one prop to your value. Note that if you only define the open prop, for example, the value prop and the other props remain auto controlled inside the component.

That's one more feature that makes Semantic UI React amazing, so easy to use, and a lifesaver when it comes to building React web application. It saves you hours of development and hundreds of lines of code.

Alright, enough talking! Let's build a piece of UI that could be useful for your next web application project.

Build Authentication Pages with Semantic UI React

In almost every web application, you need a register and login page for your users to authenticate. Let's build those pages using Semantic UI React components. Those pages will contain several top-level components from Semantic UI React including a Header, a Form, some Input fields, and a Button.

The final application can be found here: Build Authentication Pages with Semantic UI React.

We'll start by creating a React application using the create-react-app package:

npx create-react-app react-semantic-ui-app
cd react-semantic-ui-app
npm start
Enter fullscreen mode Exit fullscreen mode

Then, run the commands from above to install Semantic UI React and Semantic UI CSS. Remember to import the Semantic stylesheets in your index.js file.

Finally, install React Router so that we can easily handle routes in our React app:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Now, you should be all set! Let's start building the pages of our React app.

First things first, we need to set up the routes of our application using react-router-dom. Our app will contain only 2 routes, the /login and /register paths for the Login and Register pages respectively. Let's also handle 404 errors by redirecting the user to the Login page by default.

// App.js
import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect
} from "react-router-dom";
import "./styles.css";
// Routes
import Login from "./routes/Login";
import Register from "./routes/Register";

export default function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />
        <Redirect to="/login" />
      </Switch>
    </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

Note that I have created the Login and Register components inside the routes folder. The structure of our React app is the following:

src/
 ├── routes/
 |    ├── Login.js
 |    └── Register.js
 |
 ├── App.js
 └── index.js
Enter fullscreen mode Exit fullscreen mode

Now, let's build our pages. The structure of the Login and Register pages will be very similar. So, I will go through the Login component only and give the code for the Register page for you to read.

For both pages, we will use the Semantic UI React Grid component to center the authentication forms vertically and horizontally. Semantic UI React Grid allows grouping of content into rows and columns by using the more specific Grid.Row and Grid.Column components respectively. Have a look at the documentation for more details.

Here we'll use only one column inside our Semantic UI React Grid and pass the right props to it in order to center our content.

import React from "react";
import { Button, Form, Grid, Header } from "semantic-ui-react";

const Login = () => (
  <Grid textAlign="center" style={{ height: "100vh" }} verticalAlign="middle">
    <Grid.Column>
      { /* the authentication form goes here */}
    </Grid.Column>
  </Grid>
);

export default Login;
Enter fullscreen mode Exit fullscreen mode

Then, the content of the page will be composed of a header and an authentication form.

Semantic UI React provides us with a Header component to display an HTML heading tags, that is, h1 down to h6. We can specify which of the header tags to be used by using the as props.

<Header as="h2" />
Enter fullscreen mode Exit fullscreen mode

The Semantic UI React Header component also has a few shorthands we can use to declare the content of the heading tag. So, let's add a logo and some text to it.

<Header
  as="h2"
  textAlign="center"
  image="/assets/logo_square.svg"
  content="Sign in to your account"
  style={{ marginBottom: "32px" }}
/>
Enter fullscreen mode Exit fullscreen mode

Note that I have also added some styling to center the text and add a bottom margin.

Let's now write the authentication form. Once again, Semantic UI React provides us with a Form component and a Form.Input sub-components in order to create a form with user input fields in a clean and organized way. Not to mention that we can use the Semantic UI React Button component to add a styled submit button to our Form.

<Form size="large">
  <Form.Input
    fluid
    icon="mail"
    iconPosition="left"
    placeholder="E-mail address"
  />
  <Form.Input
    fluid
    icon="lock"
    iconPosition="left"
    placeholder="Password"
    type="password"
  />
  <Button
    type="submit"
    color="purple"
    fluid
    size="large"
    style={{ marginBottom: "32px" }}
  >
    Sign in
  </Button>
</Form>
Enter fullscreen mode Exit fullscreen mode

Note at how easy it is to create a nice form for our login page. It is very concise and does not require a lot of code.

Here we have 2 input fields, one for the user email address, and another one for the password. Using shorthands on the Form.Input component we also added an icon on the left of each field.

Finally, let's add a link to the registration page, using react-router, in case the user does not have an account yet and want to create one.

import { Link } from "react-router-dom";

const Login = () => (
  <Grid textAlign="center" style={{ height: "100vh" }} verticalAlign="middle">
    <Grid.Column>
      ...
      <p>
        Not a member? <Link to="/register">Sign up now</Link>
      </p>
    </Grid.Column>
  </Grid>
);
Enter fullscreen mode Exit fullscreen mode

That's it, folks! In a few easy steps, we have built a nice and styled page using Semantic UI React components.

Below is the code for the Register component. It is pretty similar to the one we have created for the login page expect that it contains 2 more input fields.

import React from "react";
import { Link } from "react-router-dom";
import { Button, Form, Grid, Header } from "semantic-ui-react";

const Register = () => (
  <Grid textAlign="center" style={{ height: "100vh" }} verticalAlign="middle">
    <Grid.Column>
      <Header
        as="h2"
        textAlign="center"
        image="/assets/logo_square.svg"
        content="Create your account"
        style={{ marginBottom: "32px" }}
      />
      <Form size="large">
        <Form.Group widths="equal">
          <Form.Input
            fluid
            icon="user"
            iconPosition="left"
            placeholder="First name"
          />
          <Form.Input
            fluid
            icon="user"
            iconPosition="left"
            placeholder="Last name"
          />
        </Form.Group>
        <Form.Input
          fluid
          icon="mail"
          iconPosition="left"
          placeholder="E-mail address"
        />
        <Form.Input
          fluid
          icon="lock"
          iconPosition="left"
          placeholder="Password"
          type="password"
        />
        <Button
          type="submit"
          color="purple"
          fluid
          size="large"
          style={{ marginBottom: "32px" }}
        >
          Sign up
        </Button>
      </Form>
      <p>
        Already a member? <Link to="/login">Sign in</Link>
      </p>
    </Grid.Column>
  </Grid>
);

export default Register;
Enter fullscreen mode Exit fullscreen mode

Conclusion

Once again, the final application can be found here: Build Authentication Pages with Semantic UI React.

In this article, I introduced you to the Semantic UI framework and how it helps to create styled web applications fast. But more importantly, I introduce you to the React version of this framework, Semantic UI React, which allows us to use Semantic UI in our React application. Semantic UI React provides us with a lot of pre-defined React components we can use out of the box to compose our App very quickly. Lastly, we went over a practical example by building authentication pages with Semantic UI React components only.

Top comments (0)