Make a Mobile App with Reactjs in Minutes
Ken Wheeler (@ken_wheeler)
React allows front-end developers to build their apps in an unprecedented way. It has many good things: such as single-stream, simple-life-cycle, voice-over-group.
Reapp is a framework based on React, which has recently been announced. It is a mobile platform that is designed for performance and productivity. You can think of it as a well-crafted UI composition with a good editing system and a lot of useful tools that will allow you to easily build your own apps.
Reapp gives us a bunch of great stuff:
- Complete Mobile UI Components
- "Reapp new" generates an available app
- "Reapp Run" to activate your ES6 app, and can be updated without the need to re-activate
- Theme and animation
- Routing and Packet requests
- Using Cordova to create an applied
Our goal
To demonstrate the Reapp, we will create an adaptation that allows you to examine the Flickr API and then display the results in the gallery. With this tutorial, it will occupy you in less than half an hour! "
Start
First you have to install node, and then we perform the installation of the sudo npm install -g reapp
Reapp CLI. After the installation, execute reapp new flickrapp
. Finally, cd flickrapp
again reapp run
.
You'll see the following:
Open the localhost:3010 in your browser and you'll see the Reapp application:
Tip: In Chrome's developer tool, you can open the virtual mobile device and move it to see what you're using.
Great! Now we have completely run a full React with the Reapp set of components. Look at the document structure:
<!-- lang: js -->/app components/ home/ Sub.jsx App.jsx Home.jsx app.js routes.js/assets
Reapp gave us some of the demo pages, as you can see, on the inside . app/components
, a typical REST structure. ./app/app.js
is the portal we use, it will load Reapp and execute our routes, and the routes will be ./app/routes.js
configured.
start with the vision
We generate an adaptation, and the Reapp-generated apps include many embedded pages, and we don't need that much, just a single page. Let's get it simple. In the inside routes.js
, we can change it to this:
<!-- lang: js -->module.exports = ({ routes, route }) => routes(require, route(‘app‘, ‘/‘, { dir: ‘‘ }) );
This specifies the root route (http://localhost:3010) to app
which the Reapp router will automatically find ./components/App.jsx
.
Now we can safely Home.jsx
home/Sub.jsx
Delete the files because we don't need more images. Of course you can keep them, and you'll use them after all you want.
In the App.jsx
file, we can simplify it like this:
<!-- lang: js -->import React from ‘react‘;import View from ‘reapp-ui/views/View‘;export default React.createClass({ render() { var { photos } = this.state; return ( <View title="Flickr Search" styles={{ inner: { padding: 20 } }}> <p>Hello World</p> </View> ); }});
If you refresh, you can see that the interface becomes an empty view plus a new title in the top "Flickr Search".
get the numbers from Flickr .
Now we have the interface but not logically. Before we connect the buttons and display the photos, it's very natural to use the React method to get the photo numbers from Flickr first. First, you have to have a Flickr account, and API key. You didn't? Dot here.
Fill it out (without the account you register), and give it to your public Key to save it to the App.jsx
amount of silence. You also need to check the URL of the photo, you can find in the API Explorer, too troublesome I give you directly to the Https://www.flickr.com/services/api Explore/flickr.photos.search.
It looks like this:
<!-- lang: js -->const key = ‘__YOUR_KEY_HERE__‘;const base = ‘https://api.flickr.com/services/rest/?api_key=${key}&format=rest&format=json&nojsoncallback=1‘;
That "Your_key_here" is where you put the KEY.
Note: const
This is the new feature of next-generation JavaScript, which is ES6. It looks like a change, but it doesn't change after it's set. How should we adjust it in the application? Reapp has built-in [Webpack][13]
editing system to support ES6 new features!
Below, give us the React definition, so that our group getInitialState()
can follow the photo numbers we've got. We add it to the back side of the first React.createClass
. Because we save the photos in a list, we have a list:
<!-- lang: js -->getInitialState() { return { photos: [] }},
So we can get in the rendering method and interview this.state.photos
. In the UI, we need a button and a key input box:
<!-- lang: js -->import Button from ‘reapp-ui/components/Button‘;import Input from ‘reapp-ui/components/Input‘;
Then update the render()
method:
<!-- lang: js -->render() { var { photos } = this.state; return ( <View title="Flickr Search"> <Input ref="search img-responsive" /> <Button onTap={this.handleSearch}>Search Images</Button> <div className="verticalCenter"> {!photos.length && <p>No photos!</p> } </div> </View> ); }
And then you get satisfied and it becomes this:
Simple to explode! But there are some areas that need to be noted. First, do you see the ref of the input box? Ref is a reference, which allows us to follow DOM elements in class. We'll use it later to get the values that are entered on the interface.
Also, please look at the div className="verticalCenter"
. Two points: Because we are using JSX to encode JS to the image (more detailed here), we can not use the normal class
nature, so we use to set the className
class. verticalCenter
the other component is provided by Reapp, which puts the elements in the middle of our page.
Finally, you see the Sex on the button onTap
? It points this.handleSearch
. But we don't have a handlesearch method. React needs it, so let's finish it. First, install the npm install --save superagent
Superagent that we need. And then leads into:
<!-- lang: js -->import Superagent from ‘superagent‘;
And then the definition handlesearch:
<!-- lang: js --> handleSearch() { let searchText = this.refs.search.getDOMNode().value; Superagent .get(`${base}&method=flickr.photos.search&text=${searchText}&per_page=10&page=1`, res => { if (res.status === 200 && res.body.photos) this.setState({ photos: res.body.photos.photo }); }); },
A few new notes:
this.refs.search.getDOMNode()
Returns the input DOM nodes, which is where we put the "search" ref
${base}
Grab the URL that we define in constant
this.setState
will help us get the picture, there are the numbers that we've been defining here getInitialState
. this.state.photos
Show Flickr Photos
Now we've got Flickr photos and put them in the state. The last step is shown. You can add a console.log to the first line of the Render method to see what Flick gave you back:
<!-- lang: js -->render() { console.log(this.state.photos); // ... rest of render}
In the Control pool table you will see that Flickr has returned to you a pair of images that have a lot of sexual nature, which depends on your request URL. You can look at the URL of Flickr in this help page.
You see, I'm here to deal with my URL, and I put a simple method in the category:
<!-- lang: js -->getFlickrPhotoUrl(image) { return `https://farm${image.farm}.staticflickr.com/${image.server}/${image.id}_${image.secret}.jpg`;},
This method takes our Flickr image and turns it into the URL we need to display. Now, let's edit Handlesearch and setState
adjust:
<!-- lang: js -->this.setState({ photos: res.body.photos.photo.map(this.getFlickrPhotoUrl)});
map
The method will go through our photo images and then pass them on to the getflickrphotourl and convert them into URLs. And then you can show it!
We put Reapp's Gallery components into the future:
<!-- lang: js -->import Gallery from ‘reapp-ui/components/Gallery‘;
In the Render method, in the <p>No photos found!</p>
following:
<!-- lang: js -->{!!photos.length && <Gallery images={photos} width={window.innerWidth} height={window.innerHeight - 44} />}
The Gallery group will take these three pieces, and then the full-screen mode shows the pictures, and you can swipe left and right to switch them. Here, we have done our work. Look at your browser to see how it works.
Note: why window.innerHeight -44
? Because we set the titlebar high of 44. Of course, there are other better ways to deal with it, but it is easy to be violent and easy to use, not to ask for the right quality.
the last
So far we've done a good job, but there are a lot of places we can adjust. For example, we are not concerned about the picture library now. Of course, if we add a onClose to it, it's still possible. But we still need to update our state when it's closed. Okay, here's a simple look:
<!-- lang: js -->onClose={() => this.setState({ photos: [] })}
In the same way, our input box looks ugly dead. Let's add a special effect, border,margin and placeholder:
<!-- lang: js --><Input ref="search" placeholder="Enter your search" styles={{ input: { margin: ‘0 0 10px 0‘, border: ‘1px solid #ddd‘ }}} />
is not very handsome!
Full Password
Well, all of our codes are written in ./components/App.jsx
the inside. It's simple, it's easy to understand, and it uses some cool ES6. To read the full version:
<!--lang:js-->import React from ' React ', import View from ' Reapp-ui/views/view ', import Button from ' Reapp-ui/compo Nents/button '; import Input from ' Reapp-ui/components/input ', import Superagent from ' Superagent ', import Gallery from ' Reapp-ui/components/gallery '; const My_key = ' __your_key_here__ '; const base = ' https://api.flickr.com/services/rest/? Api_key=${my_key}&format=rest&format=json&nojsoncallback=1 '; export default React.createclass ({ Getinitialstate () {return {photos: []}},//see:https://www.flickr.com/services/api/misc.urls.html GETF Lickrphotourl (image) {return ' https://farm${image.farm}.staticflickr.com/${image.server}/${image.id}_${ Image.secret}.jpg '; }, Handlesearch () {Let SearchText = This.refs.search.getDOMNode (). value; Superagent. Get (' ${base}&method=flickr.photos.search&text=${searchtext}&per_page=10&page=1 ', res = = {if (Res.status = = && Res.body.photos) this.setstate({Photos:res.body.photos.photo.map (This.getflickrphotourl)}); }); }, Render () {var {photos} = this.state; Return (<view title= "Flickr search" styles={{inner: {padding:20}}}> <input ref= "Search" Placeho Lder= "Enter your Search" styles={{input: {margin: ' 0 0 10px 0 ', border: ' 1px solid #ddd ' }}}/> <button ontap={this.handlesearch}>search images</button> <div clas Sname= "Verticalcenter" > {!photos.length && <p>no photos!</p>} {!! Photos.length && <gallery onclose={() = This.setstate ({photos: []})} Images={photos} width={window.innerwidth} height={window.innerheight-44}/> } </div> </View>); }});
Next Step
We can take this as a step forward. We can first show a list of images and click on them to show gallery. Reapp also provides its composition files, so you can see what you need to add it to your apps. Reapp also has several examples that they provide: the Kitchen Sink demo and the Hacker News App.
Take a direct look at the password
If you want to look directly at the code for this example, you can clone the project directly. It includes everything you need, and of course you have to register one yourself if you want to test it except for Flickr API key.
The steps to activate this project:
- Installed NODE/NPM, as well as Reapp:
sudo npm install -g reapp
- Cloning Project:
git clone [email protected]:reapp/flickr-demo
- Installation relies on:
npm install
- Activation Service:
reapp run
- Enter http://localhost:3010 in the browser to see the effect
You should still want to see Reapp start, if you want to go deep and look at the UI composition file.
Happy hacking!
Learning React.js: Use Reactjs 30 minutes to create a mobile