joppot

コピペで絶対動く。説明を妥協しない

プログラミング

Tutorial to create a modal using react-modal

投稿日:2018年11月12日 更新日:


Abstract

Hello everyone it’s me candle. In this time, let’s create a modal with react-modal.

React-modal is a library which can create and handle a modal easily.
But

However, react-modal is not easy if you try to actually use it. it is necessary to incorporate state management, action, design etc.

In this article, I will explain it like a tutorial and we will make a modal together.

Condition

  1. You have a react knowledge.
  2. You installed create-react-app.

Set up development env

If you already have a some react project, you would use it.
Otherwise, you don’t have a any project, please create a new project with this command.

create-react-app rmodal
cd rmodal

Install Faker

Faker is necessary for explanation, so it is not absolutely necessary.
We installed it to generate dummy data of state using Faker.js.

yarn add --dev faker

Edit the App.js

We will make a container using faker. Open src/App.js and edit like this.

import React, { Component } from 'react'
import Faker from 'faker'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      users: [],
      user: {
        products: []
      }
    }
  }

  componentWillMount() {
    for (let i = 0; i < 10; i++) {
      let products = []

      for (let j = 0; j < 6; j++) {
        const product = {
          name: Faker.commerce.productName(),
          price: Faker.commerce.price(),
          image: Faker.image.food(30, 40),
        }
        products = [...products, product]
      }

      const user = {
        name: Faker.internet.userName(),
        email: Faker.internet.email(),
        avatar: Faker.internet.avatar(),
        products: products,
      }
      this.setState(prevState => ({
        users: [...prevState.users, user],
      }))
    }
  }

  renderUsers(user) {
    return (
      <div style={{ border: 'solid 1px #eee' }}>
        <img src={user.avatar} alt={user.name} width="50" height="50" />
        <h4>Name: {user.name}</h4>
        <h4>Email: {user.email}</h4>
      </div>
    )
  }

  render() {
    return <div>{this.state.users.map(user => this.renderUsers(user))}</div>
  }
}

export default App

I don’t explain a detail, anyway it works fine like the below image.

Our purpose is to display the modal which has these user’s products list when you click the user.

The part is here.

const user = {
  name: Faker.internet.userName(),
  email: Faker.internet.email(),
  avatar: Faker.internet.avatar(),
  products: products,
}

Ok ready to start.

Install react-modal

Execute the command to install react-modal in the terminal.

yarn add react-modal

Import react-modal

First we import react-modal into arbitrary file.
I will write it into src/App.js.

import Modal from 'react-modal'

react-modal’s setAppElement

Next, we will write Modal.setAppElement('#yourAppElement').
This is a setting to clarify the relationship with other contents when a modal is displayed.

If you build the project with create-react-app command, there are doms like this in the public/index.html.

 <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>

You can see id="root". Let’s write it before class App ofsrc / App.js.

Modal.setAppElement('#root')

The state for modal

We will make a state to management whether the modal is open or closed.
Add modalIsOpen: false state to this.state={} of constructor(props).
The modal is closed as a default, so set up false.

 constructor(props) {
    super(props)
    this.state = {
      users: [],
      user: {
        products: []
      },
      modalIsOpen: false
    }
  }

Functions to open and close modal

Next, please write these two functions in the class anywhere you like.

  openModal() {
    this.setState({modalIsOpen: true});
  }

  closeModal() {
    this.setState({modalIsOpen: false});
  }

Create a css json of modal

The react-modal’s modal is defined by json.
The default css code is here. In this time we will use this code without changing.

Let’s write it downward.

const customStyles = {
    overlay: {
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(255, 255, 255, 0.75)'
    },
    content: {
      position: 'absolute',
      top: '40px',
      left: '40px',
      right: '40px',
      bottom: '40px',
      border: '1px solid #ccc',
      background: '#fff',
      overflow: 'auto',
      WebkitOverflowScrolling: 'touch',
      borderRadius: '4px',
      outline: 'none',
      padding: '20px'
    }
  };

Function to display contents when modal is opened

The contents of the modal will display products inuser state.
So we will create a function like this.

  renderProducts(product) {
    return (
      <div style={{ border: 'solid 1px #eee' }}>
        <img src={product.image} alt={product.name} width="50" height="50" />
        <h4>Name: {product.name}</h4>
        <h4>Price: {product.price}</h4>
      </div>
    )
  }

JSX of modal

Let’s make a modal JSX. Write the below code into the render() function.

 render() {
    return (
      <div>
        {this.state.users.map(user => this.renderUsers(user))}
        <Modal
          isOpen={this.state.modalIsOpen}
          onRequestClose={this.closeModal.bind(this)}
          style={customStyles}
          contentLabel="Example Modal"
        >
          <h2>
            {this.state.user.name}
            の制作物
          </h2>
          <button onClick={this.closeModal.bind(this)}>Close</button>
          {this.state.user.products.map(product => this.renderProducts(product))}
        </Modal>
      </div>
    )
  }

Display modal

We edit the function so that it displays the modal when you click a user. Change the openModal() function.

  openModal(user) {
    this.setState({
      user: user,
      modalIsOpen: true,
    })
  }

Edit the renderUsers(user) function. This DOM calls the openModal function with onClick.

  renderUsers(user) {
    return (
      <div style={{ border: 'solid 1px #eee' }} onClick={this.openModal.bind(this, user)}>
        <img src={user.avatar} alt={user.name} width="50" height="50" />
        <h4>Name: {user.name}</h4>
        <h4>Email: {user.email}</h4>
      </div>
    )
  }

This is completed. Let’s run it.

Check the modal

Start the server.

yarn run start

Check it on the browser.

To close a modal, you can click outside the modal or click the close button.

It went well.

The whole of code

I write all the code I explained at the end.

import React, { Component } from 'react'
import Faker from 'faker'
import Modal from 'react-modal'

Modal.setAppElement('#root')

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      users: [],
      user: {
        products: [],
      },
      modalIsOpen: false,
    }
  }

  componentWillMount() {
    for (let i = 0; i < 10; i++) {
      let products = []

      for (let j = 0; j < 6; j++) {
        const product = {
          name: Faker.commerce.productName(),
          price: Faker.commerce.price(),
          image: Faker.image.food(30, 40),
        }
        products = [...products, product]
      }

      const user = {
        name: Faker.internet.userName(),
        email: Faker.internet.email(),
        avatar: Faker.internet.avatar(),
        products: products,
      }
      this.setState(prevState => ({
        users: [...prevState.users, user],
      }))
    }
  }

  openModal(user) {
    this.setState({
      user: user,
      modalIsOpen: true,
    })
  }

  closeModal() {
    this.setState({ modalIsOpen: false })
  }

  renderProducts(product) {
    return (
      <div style={{ border: 'solid 1px #eee' }}>
        <img src={product.image} alt={product.name} width="50" height="50" />
        <h4>Name: {product.name}</h4>
        <h4>Price: {product.price}</h4>
      </div>
    )
  }

  renderUsers(user) {
    return (
      <div style={{ border: 'solid 1px #eee' }} onClick={this.openModal.bind(this, user)}>
        <img src={user.avatar} alt={user.name} width="50" height="50" />
        <h4>Name: {user.name}</h4>
        <h4>Email: {user.email}</h4>
      </div>
    )
  }

  render() {
    return (
      <div>
        {this.state.users.map(user => this.renderUsers(user))}
        <Modal
          isOpen={this.state.modalIsOpen}
          onRequestClose={this.closeModal.bind(this)}
          style={customStyles}
          contentLabel="Example Modal"
        >
          <h2>
            {this.state.user.name}
            の制作物
          </h2>
          <button onClick={this.closeModal.bind(this)}>Close</button>
          {this.state.user.products.map(product => this.renderProducts(product))}
        </Modal>
      </div>
    )
  }
}

const customStyles = {
  overlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(255, 255, 255, 0.75)',
  },
  content: {
    position: 'absolute',
    top: '40px',
    left: '40px',
    right: '40px',
    bottom: '40px',
    border: '1px solid #ccc',
    background: '#fff',
    overflow: 'auto',
    WebkitOverflowScrolling: 'touch',
    borderRadius: '4px',
    outline: 'none',
    padding: '20px',
  },
}

export default App

Conclusion

In this article I have explained the basic usage of react-modal.

You scroll in the modal and when you come to the bottom, the background page can also scroll. Also, even if you scroll outside the modal, the background page scrolls the same way. Sometime this is inconvenient, so I’d like to explain how to fix it next time.

Please adjust the design and use it.

スポンサードリンク

If you think this article is good, share it please

-プログラミング
-, , ,

執筆者:


comment

Your email address will not be published. Required fields are marked *

関連記事

Use react-simple-format in React web

Abstract Hello everyone it’s me candle. In this article we will use simple-format in react. Simple format is famous for Ruby on Rails and is commonly used. React has a legacy react-simple-format and 16g’s made. The legacy lib is not useful, so I choose 16g’s made. https://github.com/16g/react-simple-format Condition Nothing Create project If you already have a React project please use it. If not, use the following command to create it. create-react-app simple_format_sample cd simple_format_sample How to use react-simple-format First install it. yarn add @16g/react-simple-format Open a appropriate component file. I write it in src/App.js. import React, { Component } from …

Using sphinx how to generate documents of python classes and functions

Abstruct Hello everyone it’s me candle. In this article I will explain how to make documents about classes and functions with Sphinx automatically. condition I will explain it using Python 3, but I think that it will probably work with python 2 as well. Prepare test files Create a main.py and dog.py. touch main.py dog.py Write this to the main.py from dog import Dog def main(): dog = Dog() dog.show_name() if __name__ == "__main__": main() Open the dog.py and write it. class Dog(object): def __init__(self, name="bob"): self.name = name def bark(): print("Bow Wow") def show_name(self): print(self.name) def get_name(self): return self.name …

Create plantUML with emacs using plantuml-mode

Autumn leaves on wood table Abstract Hello everyone it’s me candle. In this time, we will introduce plantuml-mode of emacs supporting plantUML. plantuml-mode has three functions. Syntax highlight Autocomplete Display UML preview There are plenty of settings, so let’s do it patiently. Precondition You had plantuml command I installed plantuml with brew. but it is ok you prepare jar file. If you don’t have it yet, please refer to here. Build PlantUML environment on Mac using brew Install plantuml-mode The latest version of plant-mode is not yet registered in el-get packages, so we will get it from github directly. For …

How to fix the background scroll of react-modal

Abstract Hello everyone it’s me candle. This time I will solve the react-modal background moving problem when you scroll. Condition You use react Completed sample code If you want to run the sample code actually, you would need to install two libraries before. faker is installed for dummy data generation. yarn add faker react-modal First, I will write the sample code of the completed version. This is described in src/App.js. import React, { Component } from 'react' import Faker from 'faker' import Modal from 'react-modal' Modal.setAppElement('#root') class App extends Component { constructor(props) { super(props) this.state = { users: [], user: …

4 functions of scikit-learn preprocesses data such as machine learning

Abstract Hello every one this is candle. In this time we will prreprocess a data with scikit-learn which is machine learning library of python. We will use scikit-learn called With scikit-learn you can use what is called a converter, and you can convert the input data with fit_transform () method.Since there are many converters, I will introduce the following four converters that are often used in machine learning. Imputer StandardScaler MinMaxScaler OneHotEncorder Condition Python3 scikit-learn 0.19.1 For running sample code, you need numpy aside from these libs.


I work in the venture company as a CTO. I start to write program in University, first I learned java, C++ and PHP. In the company, I'm developing web services by Rails. I do like to automation.