24
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React+material-uiでコピーボタン付きのテキストボックスを作る

Last updated at Posted at 2020-02-04

こういうの

textbox.gif

準備

必要なモジュールをインストールします。

  • @material-ui: いい感じのコンポーネントを提供してくれるやつ
  • react-copy-to-clipboard: クリップボードにコピーとかしてくれるやつ

今回はyarnを使用します。
npmを使用している場合は適宜読み替えてください。

$ yarn add @material-ui/core @material-ui/icons react-copy-to-clipboard

今回はTypeScriptを使用するため、react-copy-to-clipboardの型定義ファイルもインストールします。

$ yarn add --dev @types/react-copy-to-clipboard

サンプルコード

import React, { useState } from 'react';
import FormControl     from '@material-ui/core/FormControl';
import OutlinedInput   from '@material-ui/core/OutlinedInput';
import IconButton      from '@material-ui/core/IconButton';
import InputAdornment  from '@material-ui/core/InputAdornment';
import AssignmentIcon  from '@material-ui/icons/Assignment';
import Tooltip         from '@material-ui/core/Tooltip';
import CopyToClipBoard from 'react-copy-to-clipboard';

const TextBoxWithCopyButton: React.FC = () => {
  const [input,   setInput]   = useState<string>('');
  const [openTip, setOpenTip] = useState<boolean>(false);

  const handleChangeText = (e: React.ChangeEvent<HTMLInputElement>): void => {
    setInput(e.target.value);
  };

  const handleCloseTip = (): void => {
    setOpenTip(false);
  };

  const handleClickButton = (): void => {
    setOpenTip(true);
  };

  return (
    <FormControl
      variant='outlined'
    >
      <OutlinedInput
        type='text'
        value={input}
        onChange={handleChangeText}
        endAdornment={
          <InputAdornment position="end">
            <Tooltip
              arrow
              open={openTip}
              onClose={handleCloseTip}
              disableHoverListener
              placement='top'
              title='Copied!'
            >
              <CopyToClipBoard text={input}>
                <IconButton
                  disabled={input === ''}
                  onClick={handleClickButton}
                >
                  <AssignmentIcon />
                </IconButton>
              </CopyToClipBoard>
            </Tooltip>
          </InputAdornment>
        }
      />
    </FormControl>
  );
};

export default TextBoxWithCopyButton;

まとめ

細かい解説は省きます。
Material UI、それなりに綺麗なUIを簡単に作れるので本当に便利ですね。

参考

24
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?