joppot

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

プログラミング

Create the simplest drop down menu in React

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


Abstract

Hello everyone it’s me candle. In this time we will make a most simple drop down menu.

Condition

  1. 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 from 'react'

class DropDownMenu extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      listOpen: false,
    }
  }

  toggleList() {
    this.setState(prevState => ({
      listOpen: !prevState.listOpen,
    }))
  }

  handleClickMenu(val) {
    this.setState({
      listOpen: false,
    })
    alert(val)
  }

  render() {
    const { listOpen } = this.state
    return (
      <div style={styles.dropDownMenu}>
        <div onClick={this.toggleList.bind(this)} style={styles.menuButton}>
          menu
        </div>
        {listOpen && (
          <div style={styles.menuBox}>
            <div style={styles.menuContent}>
              <div onClick={this.handleClickMenu.bind(this, 1)}>menu 1</div>
            </div>
            <div style={styles.menuContent}>
              <div onClick={this.handleClickMenu.bind(this, 2)}>menu 2</div>
            </div>
            <div style={styles.lastMenuContent}>
              <div onClick={this.handleClickMenu.bind(this, 3)}>menu 3</div>
            </div>
          </div>
        )}
      </div>
    )
  }
}

const styles = {
  dropDownMenu: {
    position: 'relative',
  },
  menuButton: {
    display: 'inline',
    cursor: 'pointer',
    border: '1px solid black',
    padding: '3px 5px',
  },
  menuBox: {
    position: 'absolute',
    top: '23px',
    width: '120px',
    zIndex: 1,
    cursor: 'pointer',
    border: '1px solid black',
  },
  menuContent: {
    padding: '3px 5px',
    borderBottom: '1px solid black',
  },
  lastMenuContent: {
    padding: '3px 5px',
  },
}

export default DropDownMenu

Next open the src/App.js and edit like this.

import React, { Component } from 'react'
import DropDownMenu from './components/DropDownMenu'

class App extends Component {
  render() {
    return (
      <div>
        <p>hello menu</p>
        <DropDownMenu />
      </div>
    )
  }
}

export default App

Launch server.

yarn run start

Click the “menu” button and the menu appears, and click the “menu” button again then close it.

Click the contents of menu, an alert window displays and close the dropdown menu.

Click outside the menu to close

After clicking the “menu” button, you need to click the “menu” button again to close it again. But many sites tend to be closed easily by clicking on other parts.

You can make it using react-onclickoutside easily.

yarn add react-onclickoutside

Open src/components/DropDownMenu.js and edit.
Write this at the top of file.

import onClickOutside from 'react-onclickoutside'

Create a new function.

  handleClickOutside() {
    this.setState({
      listOpen: false,
    })
  }

Edit the part of export default DropDownMenu at the bottom of file.

export default onClickOutside(DropDownMenu)

Please check with the browser. After opening the menu, click on the outside to close the menu.

This is the finished code.

import React from 'react'
import onClickOutside from 'react-onclickoutside'

class DropDownMenu extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      listOpen: false,
    }
  }

  toggleList() {
    this.setState(prevState => ({
      listOpen: !prevState.listOpen,
    }))
  }

  handleClickMenu(val) {
    this.setState({
      listOpen: false,
    })
    alert(val)
  }

  handleClickOutside() {
    this.setState({
      listOpen: false,
    })
  }

  render() {
    const { listOpen } = this.state
    return (
      <div style={styles.dropDownMenu}>
        <div onClick={this.toggleList.bind(this)} style={styles.menuButton}>
          menu
        </div>
        {listOpen && (
          <div style={styles.menuBox}>
            <div style={styles.menuContent}>
              <div onClick={this.handleClickMenu.bind(this, 1)}>menu 1</div>
            </div>
            <div style={styles.menuContent}>
              <div onClick={this.handleClickMenu.bind(this, 2)}>menu 2</div>
            </div>
            <div style={styles.lastMenuContent}>
              <div onClick={this.handleClickMenu.bind(this, 3)}>menu 3</div>
            </div>
          </div>
        )}
      </div>
    )
  }
}

const styles = {
  dropDownMenu: {
    position: 'relative',
  },
  menuButton: {
    display: 'inline',
    cursor: 'pointer',
    border: '1px solid black',
    padding: '3px 5px',
  },
  menuBox: {
    position: 'absolute',
    top: '23px',
    width: '120px',
    zIndex: 1,
    cursor: 'pointer',
    border: '1px solid black',
  },
  menuContent: {
    padding: '3px 5px',
    borderBottom: '1px solid black',
  },
  lastMenuContent: {
    padding: '3px 5px',
  },
}

export default onClickOutside(DropDownMenu)

Conclusion

When you use it in your project, you should edit the design, and use in combination with other libraries, for example link of react-router. Please challenge and try creating an easy-to-use drop down menu.

スポンサードリンク

If you think this article is good, share it please

-プログラミング
-,

執筆者:


comment

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

関連記事

Remove or allow the html tag with javascript + React and take measures against XSS

Abstract Hello everyone it’s me candle. In this time, we will write a program which displays only the permitted html tags by React and delete other tags. Notice, displaying originally html contents, it may has a security risk such as XSS. First of all, I am not a security expert, so there is a possibility of a bug in the code. Of course, I check it and test it as long as I do. If you find any vulnerabilities in the code, it would be helpful if you point out it in the post comment form. Condition Nothing Preparation of …

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: …

How to change the language form “en-US” to “en” by wordpres bogo

English 日本語 Abstract Hello everyone, It’s me candle. In this time, I will show you to customize bogo plugins. The bogo is wonderful plugin which can adapt the wordpress site to many languages as a simple. but, there is a problem that you can’t choose general English. When writing English articles, you may not always have to write it limited to country. However, you can choose ‘en-UK’, ‘en-CA’ and ‘en-US’, but ‘en’ can not be chosen in bogo. I checked the source code. The bogo got a language list from wordpress function, and there is no general English in it. …

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

Hiragino Sans How to write to change weight in css

Abstract Hello everyone it’s me candle. In this time I will show you how to write css of Hiragino Sans.The feature of Hiragino Sans is to be able to change the weight of font from 1 to 9 levels. On the other hand, there are various ways of writing css of Hiragino Sans and I did not know exactly how to write it, so I wrote a program and test it. It will help you who will use Hiragino Sans. The quick reference is released here. http://hiragino.joppot.info Condition Nothing SPONSORED LINK How to write css of Hiragino Sans From the …


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.