1
0

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 1 year has passed since last update.

【React】一定の数値になると押せなくなるカウントボタンの作成方法

Last updated at Posted at 2022-03-08

はじめに

 本記事は、プログラミング初学者、学習を進めていて疑問に思った点について調べた結果を備忘録も兼ねてまとめたものです。
 そのため、記事の内容に誤りが含まれている可能性があります。ご容赦ください。
 間違いを見つけた方は、お手数ですが、ご指摘いただけますと幸いです。

一定の数になると押せなくなるカウントボタンの作成方法

以下のように記述することで一定の数になるとカウントボタンが非活性化され押せなくなります。

※ スタイリングにstyled-componentsを使用しています。

shared_style.js
import styled from "styled-components";

export const BaseButton = styled.button`
  cursor: pointer;
  :hover {
    opacity: 0.7;
  }
  :focus {
    outline: 0;
  }
`;

export const RoundButton = styled(BaseButton)`
  width: 42px;
  height: 42px;
  border-radius: 50%;
  border: none;
  background-color: #eeeeee;
`;

CountUpButton.jsx
import React from "react";
import { RoundButton } from "../shared_style";

export const CountUpButton = ({ onClick, isDisabled }) => {
  return (
    <RoundButton onClick={onClick} disabled={isDisabled} ></RoundButton>
  )
}
CountDownButton.jsx
import React from 'react'
import { RoundButton } from '../shared_style'

export const CountDownButton = ({ onClick, isDisabled }) => {
  return (
    <RoundButton onClick={onClick} disabled={isDisabled}></RoundButton>
  )
}
App.jsx
import './App.css';
import React, { useState } from 'react';
import styled from 'styled-components';
import { CountUpButton } from './components/Buttons/CountUpButton.jsx';
import { CountDownButton } from './components/Buttons/CountDownButton.jsx';

const CountersWrapper = styled.div`
  margin: 50px 50px;
  display: flex;
  padding: 0 15px;
`;

const CountItem = styled.div`
  margin: 0 10px;
`;

const CountNum = styled.div`
  padding-top: 10px;
`;


function App() {
  const [count, setCount] = useState(1)
  const onClickCountUp = () => {
    setCount(count + 1);
  }
  const onClickCountDown = () => {
    setCount(count - 1);
  }

  return (
    <CountersWrapper>
      <CountItem>
        <CountDownButton
          onClick={() => onClickCountDown()}
          // 数量が1以下だったら、カウントダウンさせない
          isDisabled={count <= 1}
        />
      </CountItem>
      <CountItem>
        <CountNum>
          {count}
        </CountNum>
      </CountItem>
      <CountItem>
        <CountUpButton
          onClick={() => onClickCountUp()}
          // 数量が9以上だったら、カウントアップさせない
          isDisabled={count >= 9}
        />
      </CountItem>
    </CountersWrapper>
  );
}
export default App;

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?