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 *

関連記事

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.

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 created docker shortcut command with bash alias

Abstract Hello everyone it’s me candle. I will introduce easy operation of the docker command. Of course, I just created it thinking that it was useful, so please change it for much more useful. Precondition You use bash. ( Even though you use zsh or csh or something else, you edit a bit, it will work well) You use docker

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 …

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.