LoginSignup
12
8

More than 5 years have passed since last update.

Reactでinput type=fileのフォームを作っていい感じにスタイルする

Last updated at Posted at 2019-03-30

input要素って、typeがfileになると途端にスタイルが面倒くさくなりますよね。
reactでそれっぽいコンポーネントを作ったので、残しておきます。

import React, { useState } from 'react';
import styled from 'styled-components';

const Wrapper = styled.div`
  display: flex;
`;
const Label = styled.label`
  お好きにどうぞ
`;
const Input = styled.input`
  display: none;
`;
const FileName = styled.p`
  お好きにどうぞ
`;

const onChange = (event, cb, setFileName) => {
  cb(event);
  const targetName = event.target.files.item(0).name;
  setFileName(targetName);
};

const InputFile = props => {
  const [filename, setFileName] = useState('選択されていません');
  if (props.type !== 'file') return <p>typeの指定、間違ってるよ</p>;
  return (
    <Wrapper>
      <Label>
        ファイルを選択
        <Input
          {...props}
          onChange={e => onChange(e, props.onChange, setFileName)}
        />
      </Label>
      <FileName>{filename}</FileName>
    </Wrapper>
  );
};

export default InputFile;

使い方はこんな感じ

<InputFile
  type='file'
  accept='image/*'
  onChange={e => なんか好きな処理}
/>
12
8
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
12
8