joppot

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

プログラミング

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

  1. 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: {
        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,
    })
    document.body.setAttribute('style', 'overflow: hidden;')
  }

  closeModal() {
    this.setState({ modalIsOpen: false })
    document.body.removeAttribute('style', 'overflow: hidden;')
  }

  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

Launch server,

yarn run start

And when you check with the browser, such a screen will be displayed.

Perhaps the background will not move when modal is opened.

Fix modal with css

Fixing is easy, only giving css overflow hidden to the <body> tag.

Add document.body.setAttribute('style', 'overflow: hidden;') to the function that opens the modal. In sample code that is openModal().

  openModal(user) {
    this.setState({
      user: user,
      modalIsOpen: true,
    })
    document.body.setAttribute('style', 'overflow: hidden;')
  }

On the contrary, we remove this overflow: hidden when closing the modal.

Write document.body.removeAttribute('style', 'overflow: hidden;') to the function that closes the modal.

In sample code, like this.

  closeModal() {
    this.setState({ modalIsOpen: false })
    document.body.removeAttribute('style', 'overflow: hidden;')
  }

Then the background will not move.

Conclusion

Although it was a bit of a thing, actually I did trial and error and twists and turns before finding this way.
Good React life for you.

スポンサードリンク

If you think this article is good, share it please

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

執筆者:


comment

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

関連記事

Create the simplest drop down menu in React

Abstract Hello everyone it’s me candle. In this time we will make a most simple drop down menu. Condition Knowledge of react Preparation We create a react project with the below command. create-react-app hello-menu Open src/App.js and write this. import React, { Component } from 'react' class App extends Component { render() { return ( <div> <p>hello menu</p> </div> ) } } export default App Create a components directory in the src directory. mkdir src/components Create a DropDownMenu.js file in the src/components directory. touch src/components/DropDownMenu.js Now on ready. Create a Drop down menu Open the src/components/DropDownMenu.js and write these. import …

React Project development environment building command create-react-app is too convenient

English 日本語 Abstract Hello everyone It’s me candle. In this time we will build a “react” development environment with create-react-app command and try to hello world. Past react development was created by installing babel and other packages from npm on your own using gulp or webpack. Past react development installed babel and other packages from npm and built servers with gulp and webpack. If you use the create-react-app command, you can create react environment easily. Let’s do it. Precondition Node is already installed

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.

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 …

Customize wordpress bogo plugin’s short code

English 日本語 Abstract Hello everyone, It’s me candle. In this time, I will show you how to customize wordpress bogo short code. The items to introduce are these. The flag display or hide Change the text Related article How to change the language form “en-US” to “en” by wordpres bogo Precondition WordPress bogo has been installed You can edit the theme of wordpress


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.