📷

MUI (TypeScript)で画像をラジオボタンの選択肢にする

2022/06/08に公開

MUI で画像をラジオボタンの選択肢にする方法です。

画面のイメージ

Image from Gyazo

コード

import React from 'react'
import ImageList from '@mui/material/ImageList'
import ImageListItem from '@mui/material/ImageListItem'
import Radio from '@mui/material/Radio'
import RadioGroup from '@mui/material/RadioGroup'
import FormControl from '@mui/material/FormControl'

type Props = {}

const Component: React.FC<Props> = props => {
  const imageUrls = [
    // @see https://www.irasutoya.com/search/label/%E5%8B%95%E7%89%A9
    'https://1.bp.blogspot.com/-2h8yYyNWPcQ/X3hF2mFnGjI/AAAAAAABbkU/oAne7S28I7UN3crhUPdDIJDi5SMuzkSAgCNcBGAsYHQ/s180-c/animal_hitsuji_horn.png',
    'https://1.bp.blogspot.com/-bsDqhegOqEs/XzXkwT_HMII/AAAAAAABalY/Uj-hIQFuplsJ4_nU4LAeF6rwG-_yRDbsQCNcBGAsYHQ/s180-c/animal_moose.png',
    'https://1.bp.blogspot.com/-c-OqcO_Duvo/XxU0Tix8y8I/AAAAAAABaJA/WBNfRQv9hfgAqOpnqBbvyFXUVp0i04LJQCNcBGAsYHQ/s180-c/animal_wallaby_kangaroo.png'
  ]

  const [selectedImageUrl, setSelectedImageUrl] = React.useState(imageUrls[0])

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedImageUrl(e.target.value)
  }

  return (
    <FormControl sx={{height: 1}}>
      <RadioGroup
        value={selectedImageUrl}
        onChange={handleChange}
        sx={{height: 1}}
      >
        <ImageList
          variant='woven'
          cols={2}
          gap={8}
        >
          {imageUrls.map((imageUrl, i) => (
            <Radio
              key={i}
              value={imageUrl}
              icon={
                <ImageListItem>
                  <img
                    src={`${imageUrl}?w=164&h=164&fit=crop&auto=format`}
                    srcSet={`${imageUrl}?w=164&h=164&fit=crop&auto=format&dpr=2 2x`}
                    loading='lazy'
                  />
                </ImageListItem>
              }
              checkedIcon={
                <ImageListItem sx={{border: 4}}>
                  <img
                    src={`${imageUrl}?w=164&h=164&fit=crop&auto=format`}
                    srcSet={`${imageUrl}?w=164&h=164&fit=crop&auto=format&dpr=2 2x`}
                    loading='lazy'
                  />
                </ImageListItem>
              }
            />
          ))}
        </ImageList>
      </RadioGroup>
    </FormControl>
  )
}
export default Component

参考

https://mui.com/material-ui/react-radio-button/
https://mui.com/material-ui/react-image-list/

Special thanks

https://www.irasutoya.com/

Discussion