리액트 연습 코드 모음
2023. 3. 31. 14:24ㆍ개발/토막난 상식
반응형
리액트 날씨
import React, { useEffect, useState, useRef } from "react";
import axios from 'axios';
export function Weather({ }) {
//시계
useEffect(() => {
navigator.geolocation.getCurrentPosition(naviGood, naviBad)
const id = setInterval(() => {
setTime(new Date());
}, 1000);
return (() => clearInterval(id))
}, []);
const [time, setTime] = useState(new Date());
//날씨
const [weather, setWeather] = useState({});
const naviGood = (position) => {
const lon = position.coords.longitude;
const lat = position.coords.latitude;
const API_KEY = "키키ㅣ키키키키키키키";
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
fetch(url)
.then((response) => response.json())
.then((data) => {
setWeather(data)
console.log(data)
console.log(data.name)
console.log(data.weather[0].main)
});
}
const naviBad = () => {
alert("위치를 못찾음")
}
useEffect(()=>{
console.log("weather : ", weather);
},[weather])
return(
<>
<h1>현제 시각</h1>
<span>{time.toLocaleTimeString()}</span>
<h1>날씨는</h1>
<div className="header_weather">
<div id="weather">
<span>{weather.name}의 날씨는</span>
<span>
{weather.weather && weather.weather.length > 0 ?
weather.weather[0].main + "/" +weather.main.temp + "°C`"
:
"default"
}
</span>
</div>
</div>
</>
);
}
메모장
import React, { useEffect, useState } from "react";
import "./Todolist.css"
import LimeHeader from "features/common/layout/components/LimeHeader";
export function ToDoList({ }) {
const [toDo, setToDo] = useState("");
const [toDos, setToDos] = useState([]);
const onChange = (event) => setToDo(event.target.value);
const onSubmit = (event) => {
event.preventDefault();
if (toDo === "") {
return;
}
setToDos((currentArray) => [toDo, ...currentArray]);
setToDo("");
};
return(
<>
<LimeHeader
title="메모장"
/>
<h1>갯수 ({toDos.length})</h1>
<form onSubmit={onSubmit}>
<input
onChange={onChange}
value={toDo}
type="text"
placeholder="Write your to do..."
/>
<button className="button">추가하기</button>
</form>
<hr />
<ul>
{toDos.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</>
);
}
제목 바꾸기 & 클릭
import React, { useEffect, useState } from "react";
import { useTitle } from "utils/hooks/useTitle";
// 버튼 스타일
const btnStyle = {
width: "100px",
color: "white",
background: "black",
padding: ".375rem .75rem",
border: "1px solid teal",
borderRadius: ".25rem",
fontSize: "1rem",
lineHeight: 1.5,
margin: "10px"
};
//스타일이 적용된 버튼
const ChillBtn = ({onClickButton, title}) =>{
return(
<>
<button style={btnStyle} onClick={onClickButton} >{title}</button>
</>
)
}
// 입력값
const useInput = (initialValue, validator) => {
const [value, setValue] = useState(initialValue)
const onChange = event => {
const {
target: {value}
} = event
let willUpdate = true
if (typeof validator === "function"){
willUpdate = validator(value)
}
if (willUpdate) {
setValue(value)
}
}
return {value, onChange}
}
const Test = () => {
const [item, setItem] = useState(0)
const plusItem = () => setItem(item +1)
const minusItem = () => setItem(item -1)
const changtitle = useTitle("")
const includetext = value => !value.includes("퇴근")
const name = useInput("기본단어",includetext )
return(
<>
<h1>근성테스트 {item} </h1>
<div>
<ChillBtn
title = "더하기"
onClickButton={plusItem}
/>
<button style={btnStyle} onClick={minusItem}> 빼기 </button>
</div>
<h1>퇴근 빼고 제목 바꾸기</h1>
<input
placeholder="입력하시오"
{...name} // = value={name.value}
/>
<button onClick={()=>changtitle(name.value)}> 제목바꾸기 </button>
</>
)
}
export{Test}
nav
import React, {useState} from 'react';
import { useTitle } from 'utils/hooks/useTitle';
const useTabs = (initialTab, allTabs) => {
const [currentIndex, setCurrentIndex] = useState(initialTab)
if (!allTabs || !Array.isArray(allTabs)){
return
}
return{
currentItem: allTabs[currentIndex],
changrItem: setCurrentIndex
}
}
const content = [
{
tab: "1번구역",
content: "1번 내용",
},
{
tab: "2번구역",
content: "2번 내용",
},
{
tab: "3번구역",
content: "3번 내용",
},
]
const Test2 = () => {
const {currentItem, changrItem} = useTabs(0, content)
return (
<>
{content.map((section, index) => (
<button onClick={() => changrItem(index)} >{section.tab}</button>
))}
<div>
<h1>
{currentItem.content}
</h1>
</div>
</>
);
};
export default Test2;
antd 레이아웃
import React, { useEffect, useState } from "react";
import { Breadcrumb, Layout, Menu, Space } from 'antd';
const headerStyle = {
textAlign: 'center',
color: '#fff',
height: 64,
paddingInline: 50,
lineHeight: '64px',
backgroundColor: '#7dbcea',
};
const contentStyle = {
textAlign: 'center',
minHeight: 120,
lineHeight: '120px',
color: '#fff',
backgroundColor: '#108ee9',
};
const siderStyle = {
textAlign: 'center',
lineHeight: '120px',
color: '#fff',
backgroundColor: '#3ba0e9',
};
const footerStyle = {
textAlign: 'center',
color: '#fff',
backgroundColor: '#7dbcea',
};
const AntdPage = () => {
const { Header, Content, Footer, Sider } = Layout;
return (
<Space
length = "100vh"
direction="vertical"
style={{
width: '100%',
}}
>
<Layout
style={{
minHeight:"100vh",
}}
>
<Sider style={siderStyle}>Sider</Sider>
<Layout>
<Header style={headerStyle}>Header</Header>
<Content style={contentStyle}>Content</Content>
<Footer style={footerStyle}>Footer</Footer>
</Layout>
</Layout>
</Space>
)
};
export default AntdPage;
훅
전체화면
import React, { useEffect, useRef, useState } from "react";
import { useFullScreen } from "utils/hooks/useFullScreen";
const Test3 = () => {
const {element, triggerFull} = useFullScreen();
return(
<>
<h1>전체화면</h1>
<img
ref={element}
src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTTRHSi_7ap2mHaZtTsH7M4JIZpyuMh23OSnw&usqp=CAU" alt=""
/>
<button onClick={triggerFull}>전체화면</button>
</>
)
}
export{Test3}
import React ,{ useState, useEffect, useRef} from "react";
const useFullScreen = () => {
const element = useRef();
const triggerFull = () => {
if (element.current) {
element.current.requestFullscreen()
}
}
return {element, triggerFull}
}
export {useFullScreen}
title 변경
import React ,{ useState, useEffect } from "react";
const useTitle = (initialTitle) => {
const [title, setTitle] = useState(initialTitle)
const updateTitle = () => {
const htmlTitle = document.querySelector("title")
console.log(title);
htmlTitle.innerText = title
}
useEffect(updateTitle, [title])
return setTitle
}
export {useTitle}
코인 시세
import React, { useEffect, useState } from "react";
import LimeHeader from "features/common/layout/components/LimeHeader";
export function Coin({ }) {
const [loading, setLoading] = useState(true);
const [coins, setCoins] = useState([]);
useEffect(() => {
fetch("https://api.coinpaprika.com/v1/tickers")
.then((response) => response.json())
.then((json) => {
setCoins(json);
setLoading(false);
});
}, []);
return(
<div
style={{
width: "100%",
}}>
<LimeHeader
title={"타이틀"}
/>
<h1>The Coins! {loading ? "" : `(${coins.length})`}</h1>
{loading ? (
<strong>Loading...</strong>
) : (
<select
style={{
width: "100%",
}}
>
{coins.map((coin) => (
<option>
{coin.name} ({coin.symbol}): ${coin.quotes.USD.price} USD
</option>
))}
</select>
)}
</div>
);}
반응형
'개발 > 토막난 상식' 카테고리의 다른 글
redux-toolkit (0) | 2023.04.04 |
---|---|
.then((response) => response.data); (0) | 2023.03.31 |
re_path (django) (0) | 2023.03.31 |
TypeScript란 무엇인가? (0) | 2023.03.30 |
react-redux 사용 예시 (0) | 2023.03.30 |