Gaurav Singhal Guarav is a data scientist with a strong background in computer science and mathematics. As a developer, he works with Python, Java, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React.

Using NativeBase with React Native

5 min read 1614

Using NativeBase With React Native

React Native is a framework for building cross-platform, native apps using JavaScript and React. React Native uses JSX and a component-based UI system just like React, but instead of DOM components, React Native uses native components to create native UI elements. React Native has a very low-level API and atomic components that force you to rewrite many basic components repeatedly for each new project.

When it comes to developing the user interface, there is a lot of basic styling that is required for every component. Styling can be tedious, and you would love to avoid creating a new design system for every app you work on. Ideally, you would have a styling library that contains the basic styling for components.

That’s where NativeBase comes in. In this guide, we’ll show you how to use and customize NativeBase components in your React Native app.

What is NativeBase?

NativeBase is an open-source UI library that helps you get up and running with user interface components such as buttons, cards, input fields, and more.

Think of it as a CSS framework for building mobile apps with React Native. You can get suitable styles right out of the box. All you have to do is grab and call the component from the NativeBase library.

Installing NativeBase

Create a new React Native project using the react-native init command and then cd into the project directory.

react-native init NativeBaseIntroApp
cd NativeBaseIntroApp

Install NativeBase by running the following commands.

npm i native-base
react-native link

Basic NativeBase components

The Header component renders the header for the app. It expects its children to be the Left, Body, and Right components.

The Left component wraps the components that need to be rendered on the left portion of the header. It might be a drawer navigation icon, for example. Similarly, the Right component is a wrapper for the components that need to be displayed on the right side of the header.

The Body component serves as a wrapper for components to render at the center of the Header. The Title and Subtitle components are usually wrapped by the Body component and are used to display the header title and subtitle, respectively.

We made a custom demo for .
No really. Click here to check it out.

import React, { Component } from "react";
import {
  Container,
  Header,
  Left,
  Body,
  Right,
  Title,
  Subtitle,
} from "native-base";
export default class App extends Component {
  render() {
    return (
      <Container>
        <Header>
          <Left />
          <Body>
            <Title>Header</Title>
            <Subtitle>Example subtitle</Subtitle>
          </Body>
          <Right />
        </Header>
      </Container>
    );
  }
}

Button

The Button component is a fundamental UI element in any app. Buttons are used to indicate interactive actions on a screen, such as submitting a form.

To render a button on the screen, use the Button component. To render text inside the button, add the Text component from native-base as a child.

import React, { Component } from "react";
import { Container, Header, Content, Button, Text } from "native-base";
class App extends Component {
  render() {
    return (
      <Container>
        <Header />
        <Content>
          <Button>
            <Text>Example Button</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

export default App;

You can add a function to the onPress prop to trigger the desired functionality. There are also various button theme props, including primary, success, info, warning, danger, light, and dark.

import React, { Component } from "react";
import { Alert } from "react-native";
import { Container, Header, Content, Button, Text } from "native-base";
class App extends Component {
  showAlert = () => Alert.alert("Message", "Button Clicked!!");

  render() {
    return (
      <Container>
        <Header />
        <Content>
          <Button onPress={this.showAlert} primary>
            <Text>Interactive Button</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

export default App;

You can make the button transparent using the transparent prop and determine whether a button is disabled using the disabled prop. Likewise, to create a full-width button, you can use the fullwidth prop.

NativeBase’s Button component can also have an Icon in its children, along with the Text component.

import React, { Component } from "react";
import { Alert } from "react-native";
import { Container, Header, Content, Button, Text, Icon } from "native-base";
class App extends Component {
  showAlert = () => Alert.alert("Message", "Button Clicked!!");

  render() {
    return (
      <Container>
        <Header />
        <Content>
          <Button onPress={this.showAlert} primary fullwidth iconLeft>
            <Icon name="cog">
            <Text>Settings</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

export default App;

Card

A card is a container component that is used to show information to the user on the screen. It can contain a header, footer, contextual background colors, different types of content, and more.

The Card component adds a box shadow by default and provides spacing and alignments between cards. The CardItem component is a child component of Card and can take inputs such as Text, Button, Image, etc. A Card component can have any number of CardItem components as its children.

import React, { Component } from "react";
import {
  Container,
  Header,
  Content,
  Card,
  CardItem,
  Body,
  Text,
} from "native-base";
class App extends Component {
  render() {
    return (
      <Container>
        <Header />
        <Content>
          <Card>
            <CardItem>
              <Body>
                <Text>
                  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin
                  nulla velit, imperdiet sit amet posuere ut, luctus et quam.
                  Nam molestie pretium mauris, vitae rutrum ipsum vulputate ac.
                </Text>
              </Body>
            </CardItem>
          </Card>
        </Content>
      </Container>
    );
  }
}

export default App;

To add a header and footer in the card, use the header prop with the first instance of CardItem component and footer with the last instance of the CardItem component.

// ...
<Card>
  <CardItem header>
    <Text>Example Card Header</Text>
  </CardItem>
  <CardItem>
    <Body>
      <Text>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nulla
        velit, imperdiet sit amet posuere ut, luctus et quam. Nam molestie
        pretium mauris, vitae rutrum ipsum vulputate ac.
      </Text>
    </Body>
  </CardItem>
  <CardItem footer>
    <Text>Example Card Footer</Text>
  </CardItem>
</Card>
// ...

You can also create a touchable cart item by using the button prop on the CardItem component. The button prop is useful when you want to display more content to the user, preferably on a new screen.

// ...
<Card>
  <CardItem
    header
    button
    onPress={() => Alert.alert("Message", "Card Header Pressed")}
  >
    <Text>Example Card Header</Text>
  </CardItem>
  <CardItem>
    <Body>
      <Text>The is dummy card text.</Text>
    </Body>
  </CardItem>
  <CardItem
    footer
    button
    onPress={() => Alert.alert("Message", "Card Footer Pressed")}
  >
    <Text>Example Card Footer</Text>
  </CardItem>
</Card>
// ...

List

The List component is used to show a list of information on the screen. The List component must contain one or more ListItem components.

The ListItem component provides styling props, such as selected, icon, header, etc., to make the item look more interactive and dynamic. You can also a list item divider by using the itemDivider prop.

Under the hood, the List component is built on top of React Native’s FlatList component, so any FlatList prop is a valid List component prop.

import React, { Component } from "react";
import { Container, Header, Content, List, ListItem, Text } from "native-base";
class App extends Component {
  render() {
    return (
      <Container>
        <Header />
        <Content>
          <List>
            <ListItem>
              <Text>Victor Wayne</Text>
            </ListItem>
            <ListItem>
              <Text>John Doe</Text>
            </ListItem>
            <ListItem>
              <Text>Jane Doe</Text>
            </ListItem>
          </List>
        </Content>
      </Container>
    );
  }
}

export default App;

The list can be also be generated dynamically from an external API using network calls. In the example below, a list of users is made from the component’s state, which is fetched from an external JSON API.

Below you can see that the Thumbnail component is used to display the user’s avatar. The Thumbnail component works similarly to React Native’s Image component, except it’s rounded and generally used to display small images, such as avatars.

import React, { Component } from "react";
import {
  Container,
  Header,
  Content,
  List,
  ListItem,
  Text,
  Left,
  Body,
  Right,
  Thumbnail,
} from "native-base";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      users: [],
      page: 1,
    };
  }

  fetchUsers = async () => {
    try {
      const res = await fetch(`${JSON_API_URL}&page=${this.state.page}`);
      const { results: users } = await res.json();
      if (this.state.page === 1) this.setState({ users });
      else this.setState({ users: [...this.state.users, ...users] });
    } catch (err) {
      console.log(err);
    }
  };

  componentDidMount() {
    this.fetchUsers();
  }

  render() {
    return (
      <Container>
        <Header />
        <Content>
          <List>
            {this.state.users.map((user) => (
              <ListItem avatar key={user.id}>
                <Left>
                  <Thumbnail source={{ uri: user.image_url }} />
                </Left>
                <Body>
                  <Text>{user.name}</Text>
                </Body>
              </ListItem>
            ))}
          </List>
        </Content>
      </Container>
    );
  }
}

Conclusion

NativeBase is an excellent library helps you to jump-start the development process. With NativeBase components, you don’t have to create fundamental components such as buttons, containers, and lists from scratch.

At the end of the day, NativeBase can save you a lot of time and effort, especially when working on more extensive apps, enabling you to work more efficiently on the business logic and not worry too much about the UI design.

To learn more, see the NativeBase documentation.

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Gaurav Singhal Guarav is a data scientist with a strong background in computer science and mathematics. As a developer, he works with Python, Java, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React.

Leave a Reply