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?

【Next.js】Chakra-UI(V3系)とReact-Reduxを使ってログイン画面を作成する

Posted at

image.png

今回は、Next.jsにReact-Reduxを使ったログインフォームを作ってみます。

React-Reduxのインストール

Redux-Toolkitのインストール

@chakra-ui/form-controlのインストール

@chakra-ui/next-js

実装

createSlice が受け取れるプロパティは
name
initialState
reducers
extraReducers

などです。

app/features/admin/userSlice.ts
import { createSlice } from "@reduxjs/toolkit";
import type { PayloadAction } from "@reduxjs/toolkit";

interface AdminUserState {
  email: string;
  password: string;
}

const initialState: AdminUserState = {
  email: "",
  password: "",
};

const userSlice = createSlice({
  name: "adminUser",
  initialState,
  reducers: {
    setEmail: (state, action: PayloadAction<string>) => {
      state.email = action.payload;
    },
    setPassword: (state, action: PayloadAction<string>) => {
      state.password = action.payload;
    },
    resetUser: (state) => {
      state.email = "";
      state.password = "";
    },
  },
});

export const { setEmail, setPassword, resetUser } = userSlice.actions;
export default userSlice.reducer;

app/store/store.ts
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "../features/admin/userSlice";

export const store = configureStore({
  reducer: {
    user: userReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

app/hooks/hooks.ts
import { useDispatch, useSelector } from "react-redux";
import type { TypedUseSelectorHook } from "react-redux";
import type { RootState, AppDispatch } from "../store/store";

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelecor: TypedUseSelectorHook<RootState> = useSelector;

app/admin/login/page.tsx
"use client";
import React from "react";
import { useState } from "react";
import {
  Button,
  Flex,
  Heading,
  Input,
  VStack,
} from "@chakra-ui/react";
import { FormControl, FormLabel } from "@chakra-ui/form-control";
import { useAppSelecor,useAppDispatch } from "../../hooks/hooks";//追加
import { setEmail,setPassword,resetUser } from "../../features/admin/userSlice";//追加
import {useForm} from "react-hook-form"

type FormValues = {
    email:string;
    password:string;
}

export default function AdminLogin() {
  const dispatch = useAppDispatch();
  const {email,password} = useAppSelecor((state)=>state.user);

  const {register,handleSubmit,reset,formState:{errors}} = useForm<FormValues>({
    defaultValues:{email,password}
  })
  const onSubmit = (data:FormValues)=>{
    dispatch(setEmail(data.email));
    dispatch(setPassword(data.password));
    alert(`送信しました。`);
    console.log(`送信内容:${data.email}${data.password}`);
  }

  const handleReset = ()=>{
    reset({email:"",password:""});//フォームの値をクリア
    dispatch(resetUser());//Reduxの状態も初期化する
  }

  return (
    <Flex
      flexDirection="column"
      width="100%"
      height="100vh"
      justifyContent="center"
      alignItems="center"
    >
      <VStack>
        <Heading>管理者ログイン</Heading>
        <form onSubmit={handleSubmit(onSubmit)}>
          <VStack alignItems="left">
            <FormControl>
              <FormLabel htmlFor="email" textAlign="start">
                メールアドレス
              </FormLabel>
              <Input
                {...register('email')}
                borderColor="blue.200"
              />
            </FormControl>
            <FormControl>
              <FormLabel htmlFor="password">パスワード</FormLabel>
              <Input
                {...register('password')}
                borderColor="blue.200"
              />
            </FormControl>
            <Button
              marginTop="4"
              color="white"
              bg="teal.400"
              type="submit"
              paddingX="auto"
            >
              ログイン
            </Button>
            <Button
              //as={Link}
              bg="white"
              color="black"
              width="100%"
            >
              新規登録はこちら
            </Button>
            <Button type="button" onClick={handleReset}>
                リセット
            </Button>
          </VStack>
        </form>
      </VStack>
    </Flex>
  );
}

サイト

【前編】Next.jsでログインフォームを実装する 〜chakra-ui×react-hook-form編〜

【React】ChakraUIにRedux、ToolKit、検証ライブラリYupを組み込んだフォーム画面を作る

【Next.js×Django連携】管理者ログイン画面を作成する方法

Next.js(React)でとりあえずReduxの状態管理一元化の恩恵を受ける方法

Chakra FormControl

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?