0
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 × TypeScript】子コンポーネントの値を親コンポーネントで使用する

Posted at

子コンポーネントの値を親コンポーネントで使用する

背景

  • ログインページを作成するときにUIとロジックでコンポーネントを分けたいと思ったため。
  • 親コンポーネントでユーザーネームを使用したい、子コンポーネントでユーザー名を入力するInputを使用したい。

親コンポーネント

Login.tsx
import React, { useState } from "react";
import LoginUI from "./LoginUI";

const Login = () => {
  const [userName, setUserName] = useState('');
  console.log(userName);

  const onUserNameChange = (value: string) => {
    setUserName(value);
  };
    return (
        <>
            {/* ログインUI */}
            <LoginUI userName={userName} onUserNameChange={onUserNameChange}/>
        </>
    );
}

export default Login;

子コンポーネント

LoginUI.tsx
import React from 'react';
import { Input } from '@nextui-org/react';

interface LoginProps {
  userName: string;
  onUserNameChange: (value: string) => void;
}

const LoginUI = ({ userName, onUserNameChange }: LoginProps) => {
  const handleNameChange = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ): void => {
    const value = event.target.value;
    onUserNameChange(value);
  };

  return (
    <>
      <Input
        labelPlaceholder="ユーザー名"
        onChange={handleNameChange}
      />
    </>
  );
};

export default LoginUI;


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