About Electron

For Electron, we took the quote from the official website

Electron is an open source library developed by Github for building cross-platform desktop applications using HTML, CSS, and JavaScript. Electron does this by merging Chromium and Node.js into the same runtime environment and packaging it as an application for Mac, Windows, and Linux.

In fact, according to my simple understanding at present, it is easy to construct an app containing webview by Electron borrowing Chromium. Then, because the underlying layer of this app is Chromium, the packaged app can also run on Windows, Linux and Mac respectively.

Since this is a WebView application, it is theoretically possible to use React to develop web functions. This article is going to explain this part.

Create a project with Electron Forge

Electron Forge is a common tool for Electron to create/publish/install Electron applications.

Create an app by using the following command

npx create-electron-app basicApp
cd basicApp
yarn start
Copy the code

Normally you can see an app as shown below

Look at SRC /index.js to see the general startup flow for Electron: CreateWindow is invoked when app is ready, and then a BrowserWindow is new. As an instance of BrowserWindow, mainWindow loads the local index.html.


const createWindow = (a)= > {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 320.height: 600
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', () = > {// Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
Copy the code

The react page will be loaded with local HTML. Note that we only need to change one line of code:

  // change loadFile to load URL.
  // mainWindow.loadFile(path.join(__dirname, 'index.html'));
  mainWindow.loadURL('http://localhost:3000/');
Copy the code

Next we’ll set up our React project

Create a page with create-react-app

mkdir react
cd react
npx create-react-app my-app
cd my-app
yarn start
Copy the code

If the previous steps are all right, you should now have a local page open in your browser http://localhost:3000/

Since Electron has been started before, now we need to make it reload the local React page. We can exit Electron by Cmd + Q first and then

cd. /.. / yarn start# Notice that the Electron is launched at this time, not react
Copy the code

Then you’ll notice that the React page is already inside Electron.

At this point, the basic structure of our electron + React simple interface is set up.

Create a simple login interface using the Material – UI

As for the Material – UI, the official website says:

The React component is used for faster and easier Web development. You can also build your own Design system, or start with Material Design.

In short, it helps you to quickly complete the UI

We install it with the following commands

Change to the react directory
cd react/my-app 
yarn add @material-ui/core @material-ui/icons
Copy the code

After installing react, start it

yarn start
Copy the code

To make the login interface, we need input fields, login buttons and other things, but the Material – UI is ready for us, we just need to modify app.js and app.css.

Here is the code

App.js is recommended to directly select all and then copy and paste 🙂

import React , { Component } from 'react';
import Button from '@material-ui/core/Button'
import OutlinedInput from '@material-ui/core/OutlinedInput';
import IconButton from '@material-ui/core/IconButton';
import InputAdornment from '@material-ui/core/InputAdornment';
import InputLabel from '@material-ui/core/InputLabel';
import FormControl from '@material-ui/core/FormControl';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import PhoneAndroid from '@material-ui/icons/PhoneAndroid';
import Lock from '@material-ui/icons/Lock';
import logo from './logo.svg';

import './App.css';


class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      password: ' '.showPassword: false,
    }
  }

  handleChange = prop= > event => {
    this.setState({
      [prop]: event.target.value,
    });
  }

  handleClickShowPassword = (a)= > {
    this.setState({
      showPassword:!this.state.showPassword
    });
  }

  handleMouseDownPassword = event= > {
    event.preventDefault();
  }

  render () {
    return (
      <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <FormControl style={{ marginTop: '5vh', width: '80vw'}} variant="outlined">
          <InputLabel htmlFor="outlined-adornment-number">Account</InputLabel>
          <OutlinedInput
            id="outlined-adornment-number"
            type='text'
            startAdornment={
              <InputAdornment position="start">
                <PhoneAndroid />
              </InputAdornment>
            }
            labelWidth={70}
          />
        </FormControl>

        <FormControl style={{ marginTop: '5vh', width: '80vw'}} variant="outlined">
          <InputLabel htmlFor="outlined-adornment-password">Password</InputLabel>
          <OutlinedInput
            id="outlined-adornment-password"
            type={this.state.showPassword ? 'text' : 'password'}
            value={this.state.password}
            onChange={this.handleChange('password')}
            startAdornment={
              <InputAdornment position="start">
                <Lock />
              </InputAdornment>
            }
            endAdornment={
              <InputAdornment position="end">
                <IconButton
                  aria-label="toggle password visibility"
                  onClick={this.handleClickShowPassword}
                  onMouseDown={this.handleMouseDownPassword}
                  edge="end"
                >
                  {this.state.showPassword ? <Visibility /> : <VisibilityOff />}
                </IconButton>
              </InputAdornment>
            }
            labelWidth={70}
          />
        </FormControl>

        <Button 
          variant="contained" 
          style={{ marginTop: '4vh', width: '80vw'}} 
          color="primary" 
          onClick={()=>{
              console.log('start to signin')
          }}
        >
          Sign In
        </Button>
      </header>
    </div>
    )
  }
}

export default App;

Copy the code

App.css only needs to change one line of background-color code

.App-header {
  /*background-color: #282c34; * /
  background-color: white;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}
Copy the code

And then go to your Eectron and see what the end result looks like

summary

In general, I think it’s pretty easy to make a desktop app using React + electron, similar to doing web development directly. Of course, I have just started, and I will continue to work on it. The github code for this article is github.com/kingbeful/L… Welcome to thumb up