React, useState 더 깊이 알기

2024. 12. 9. 10:17웹 개발

import { useState } from "react";
import styled from 'styled-components';

const ModuleProfile = styled.div`
    padding: 20px 20px;
    border: solid 1px #000;
    text-align: left;
`;

function Profile({ name }) {
    const [status, setStatus] = useState('Available');

    console.log('Profile Rendered')

    return (
        <ModuleProfile>
            <h3>
                Name: {name}
            </h3>
            <p>
                Status: {status}
            </p>
            <button onClick={
                () => setStatus('Away')
            }>
                Set Away
            </button>
            <button onClick={
                () => setStatus('Available')
            }>
                Set Available
            </button>
        </ModuleProfile>
    );
}

export default Profile

 

App.jsx

import './App.css';
import { useState } from 'react';
import styled from 'styled-components';

import Profile from "./component/Profile";

const ModuleApp = styled.div`
    text-align: left;
    button {
        margin: 0 5px;
    }
`;

function App() {
    const users = ['홍길동', '김건모', '강백호'];
    const [user, setUser] = useState(users[0]);
    const [status, setStatus] = useState(true);

    const switchStatus = () => {
        setStatus(!status);
    };

    const switchUser = () => {
        const nextIndex = (users.indexOf(user) + 1) % users.length; // 다음 유저로 순환
        setUser(users[nextIndex]);
    };

    console.log('App Rendered');

    return (
        <ModuleApp>
            <h2>
                User Profile
            </h2>
            <button onClick={switchStatus}>Toggle Status</button>
            <button onClick={switchUser}>Switch User</button>
            <p>
                {status ? 'Active' : 'Inactive'}<br />
            </p>
            <Profile name={user}></Profile>
        </ModuleApp>
    )
}

export default App;

 

결과

출처

https://www.youtube.com/watch?v=JjP2CMe_XAM&list=PLpO7kx5DnyIEADd0f0B7iWaDFVCekHd_7&index=13

'웹 개발' 카테고리의 다른 글

React, useWindowSize 커스텀 훅  (1) 2024.12.09
React, Use Effect 생명주기  (0) 2024.12.09
React, styled-components  (0) 2024.12.06
React, useContext  (0) 2024.12.05
React, 섭씨온도와 화씨온도 표시하기, Shared State  (1) 2024.12.04