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 *

関連記事

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 …

Tutorial How to use GSAP animation with React

Abstract Hello everyone it’s me candle. In this time we will use GSAP in React. The famous js library which can easily use animation is jQuery. However, it seems that compatibility between jQuery and React is bad. And there are no functions Also, as far as I know, React has no animation function that is easy to use(Yeah, Transition is). But, all times and places, it is rare case that animation is not necessary when you have created a web service. There are many candidates when using animation with React. Of course, you can import only the necessary functions and use …

React creates dummy data using Faker.js

Abstract Hello everyone it’s me candle. Let’s try to use Faker.js in React. I think that there are various purposes for using Faker.js. In many cases you will use it for testing, but this time I’d like to create a dummy react state using Faker.js. Condition You have a basic react skill create-react-app was installed Create new project First of all, create a react project. Execute the below command in your favorite directory and create a new react project. create-react-app faker-demo cd faker-demo Installation of faker Install faker with this coommand. yarn add –dev faker it’s over. Generate dummy data …

Tutorial to create a modal using react-modal

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 You have a react knowledge. 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 …

Ruby regex that does not match if there are keywords that you don’t want included in the string

Abstract Hello everyone it’s me candle. In this time I would like to create a regular expression that does not pass if keywords that I do not want included in the string match. This is such case like this. For example, the regex matches these words “Bitcoin” and “Bitcoin ~” but doesn’t match “BitcoinCash” and “Bitcoin Cash”. ○ Bitcoin ○ Bitcoin Core × BitcoinCash × Bitcoin Cash Condition Nothing Write the regex This is a regex that does not match if there are keywords that you do not want included in the string. /Keyword to include(?!Keywords you do not want …


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.