Mobile applications built with React typically use React Native for their library of choice. Ionic has a similar mission, but achieves it in a different way.
Built with the Stencil Web Component compiler, all of the Ionic components and surrounding plugin system can be incorporated into any JavaScript project.
The best thing about this is that we can keep our own build systems in place and use Ionic to “augment” our project. We’ll take a look at this by creating a React project with Create React App.
🐊 Alligator.io recommends ⤵
Fullstack Advanced React & GraphQL by Wes Bos
ⓘ About this affiliate link
Create a new React project
To create a new React project with create-react-app
, you can either use npx or install create-react-app
globally:
# Create new project without install $ npx create-react-app react-ionic --typescript # OR $ npm install create-react-app -g $ create-react-app react-ionic --typescript # Open the project in VS Code or your editor of your choice $ cd react-ionic $ code . # Run the project in the browser $ npm run start
You'll note that we can now use the --typescript
flag to generate a TypeScript project with Create React App.
Installing Ionic in our React app
Now we’ll have to install Ionic for React (@ionic/react
) and the surrounding dependencies. For React, Ionic currently depends on react-router
, so we’ll need to install that as well:
$ npm install @ionic/react react-router react-router-dom @types/react-router @types/react-router-dom
Note that @ionic/react
is still in beta at the time of this writing.
Using Ionic with React
At this stage, we can use Ionic like any other dependency in our project. Each component has been individually exported and can be imported as such.
import '@ionic/core/css/core.css'; import '@ionic/core/css/ionic.bundle.css'; import { IonApp, IonButton, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle, IonContent, IonHeader, IonTitle, IonToolbar, } from '@ionic/react'; import React, { Component } from 'react'; class App extends Component { state = { chomps: 0, }; unchomp = () => { if (this.state.chomps > 0) { this.setState({ chomps: this.state.chomps -= 1, }); } }; chomp = () => { this.setState({ chomps: this.state.chomps += 1, }); }; render() { return ( <IonApp> <IonHeader> <IonToolbar color="primary"> <IonTitle>Alligator</IonTitle> </IonToolbar> </IonHeader> <IonContent> <IonCard> <img src="https://images.unsplash.com/photo-1549240923-93a2e080e653?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2165&q=80" /> <IonCardHeader> <IonCardSubtitle>Crocco</IonCardSubtitle> <IonCardTitle> You've been chomped {this.state.chomps} times! </IonCardTitle> </IonCardHeader> <IonCardContent> <IonButton onClick={this.chomp}>Chomp</IonButton> <IonButton onClick={this.unchomp}>UnChomp</IonButton> </IonCardContent> </IonCard> </IonContent> </IonApp> ); } } export default App;
Here’s the results of our hard work: