programming/web

[React] CRUD

chanchand 2023. 8. 11. 20:24
반응형

설치

npm i create-react-app
npx create-react-app [폴더]
npm start

 

배포

npm build
npx serve -s build

 

컴포넌트

Header, Nav, Article

import './App.css';

function Header(){
  return <header>
    <h1><a href="/">WEB</a></h1>
  </header>
}

function Nav(){
  return <nav>
    <ol>
      <li><a href="/read/1">html</a></li>
      <li><a href="/read/2">css</a></li>
      <li><a href="/read/3">js</a></li>
      </ol>
  </nav>
}

function Article(){
  return <article>
    <h2>Welcome</h2>
    Hello, WEB
  </article>
}

function App() {
  return (
    <div>
      <Header></Header>
      <Nav></Nav>
      <Article></Article>
    </div>
  );
}

export default App;

 

props

import './App.css';

function Header(props){
  return <header>
    <h1><a href="/">{props.title}</a></h1>
  </header>
}

function Nav(props){
  const lis = []
  for (let i = 0; i < props.topics.length; i++){
    let t = props.topics[i];
    lis.push(<li key={t.id}><a href={'/read'+t.id}>{t.title}</a></li>)
  }
  return <nav>
    <ol>
      {lis}  
    </ol>
  </nav>
}

function Article(props){
  return <article>
    <h2>{props.title}</h2>
    {props.body}
  </article>
}

function App() {
  const topics = [
    {id:1, title:'html', body:'html is ...'},
    {id:2, title:'css', body:'css is ...'},
    {id:3, title:'js', body:'javascript is ...'}
  ]

  return (
    <div>
      <Header title="WEB"></Header>
      <Nav topics={topics}></Nav>
      <Article title="Welcome" body="Hello, WEB"></Article>
    </div>
  );
}

export default App;

 

event

event.preventDefault() : 페이지 reload가 일어나지 않도록 함

event.target : 이벤트를 유발시킨 태그를 가리킴

function(){} -> ()=>{} 로 축약 가능

function Header(props){
  return <header>
    <h1><a href="/" onClick={(event)=>{
      event.preventDefault();
      props.onChangeMode();
    }}>{props.title}</a></h1>
  </header>
}

function App() {
  return (
    <div>
      <Header title="WEB" onChangeMode={()=>{
        alert('Header');
      }}></Header>
    </div>
  );
}

export default App;

 

state / Read

Number() : 문자를 숫자로 변경

- useState() 

배열 리턴

인덱스 0 : 상태의 값을 읽을 때 사용하는 데이터

인덱스 1 : 상태의 값을 변경할 때 사용하는 함수

import { useState } from 'react';

function App() {
  const [mode, setMode] = useState('WELCOME');
  const [id, setId] = useState(null);

  const topics = [
    {id:1, title:'html', body:'html is ...'},
    {id:2, title:'css', body:'css is ...'},
    {id:3, title:'js', body:'javascript is ...'}
  ]

  let content = null;

  if (mode === "WELCOME"){
    content = <Article title="Welcome" body="Hello, WEB"></Article>
  }
  else if (mode === "READ"){
    let title, body = null;
    for (let i = 0; i < topics.length; i++){
      if (topics[i].id === id){
        title = topics[i].title;
        body = topics[i].body;
      }
    }
    content = <Article title={title} body={body}></Article>
  }

  return (
    <div>
      <Header title="WEB" onChangeMode={()=>{
        setMode('WELCOME');
      }}></Header>
      <Nav topics={topics} onChangeMode={(id)=>{
        setMode('READ');
        setId(id);
      }}></Nav>
      {content}
      
    </div>
  );
}

export default App;

 

Create

- object, arr ..

const [value, setValue] = useState();
newValues = {...value}
newValues.push(newValue)
setValue(newValues)

 

import { useState } from 'react';

function Create(props){
  return <article>
    <h2>Create</h2>
    <form onSubmit={event=>{
      event.preventDefault();
      const title = event.target.title.value;
      const body = event.target.body.value;
      props.onCreate(title, body);
    }}>
    <p><input type="text" name="title" placeholder="title" /></p>
    <p><textarea name="body" placeholder="body"></textarea></p>
    <p><input type="submit" value="Create"></input></p>
    </form>
  </article>
}

function App() {
  const [mode, setMode] = useState('WELCOME');
  const [id, setId] = useState(null);
  const [nextId, setNextId] = useState(4);
  const [topics, setTopics] = useState([
    {id:1, title:'html', body:'html is ...'},
    {id:2, title:'css', body:'css is ...'},
    {id:3, title:'js', body:'javascript is ...'}
  ]);
  if (mode === "CREATE"){
    content = <Create onCreate={(_title, _body)=>{
      const newTopic = {id:nextId, title:_title, body:_body}
      const newTopics = [...topics]
      newTopics.push(newTopic);
      setTopics(newTopics);
      setMode('READ');
      setId(nextId);
      setNextId(nextId+1);
    }}></Create>
  }
  return (
    <div>
      <Header title="WEB" onChangeMode={()=>{
        setMode('WELCOME');
      }}></Header>
      <Nav topics={topics} onChangeMode={(id)=>{
        setMode('READ');
        setId(id);
      }}></Nav>
      {content}

      <a href="/create" onClick={event=>{
        event.preventDefault();
        setMode('CREATE');
      }}>Create</a>
      
    </div>
  );
}

export default App;

 

Update

import { useState } from 'react';

function Update(props){
  const [title, setTitle] = useState(props.title);
  const [body, setBody] = useState(props.body);

  return <article>
    <h2>Update</h2>
    <form onSubmit={event=>{
      event.preventDefault();
      const title = event.target.title.value;
      const body = event.target.body.value;
      props.onUpdate(title, body);
    }}>
      <p><input type="text" name="title" placeholder="title" value={title} onChange={event=>{
        setTitle(event.target.value);
      }}/></p>
      <p><textarea name="body" placeholder="body" value={body} onChange={event=>{
        setBody(event.target.value);
      }}></textarea></p>
      <p><input type="submit" value="Update"></input></p>
    </form>
  </article>
}

function App(){
	let contextControl = null;
	
    if (mode === "UPDATE"){
        let title, body = null;
        for (let i=0; i<topics.length; i++){
          if (topics[i].id === id){
            title = topics[i].title;
            body = topics[i].body;
          }
        }

    	content = <Update title={title} body={body} onUpdate={(title, body)=>{
      		const newTopics = [...topics]
      		const updatedTopic = {id:id, title:title, body:body}
      		for (let i = 0; i < newTopics.length; i++){
        		if (newTopics[i].id === id){
          			newTopics[i] = updatedTopic;
         	 		break;
       			}
     		}
      		setTopics(newTopics);
      		setMode('READ')
    	}}></Update>
  	}
}

 

Delete

function App() {
	else if (mode === "READ"){
    let title, body = null;
    for (let i = 0; i < topics.length; i++){
      if (topics[i].id === id){
        title = topics[i].title;
        body = topics[i].body;
      }
    }
    content = <Article title={title} body={body}></Article>
    contextControl = <>
      <li><a href ={"/update/"+id} onClick={event=>{
        event.preventDefault();
        setMode('UPDATE');
      }}>Update</a></li>
      <li><input type="button" value="Delete" onClick={()=>{
        const newTopics=[]
        for (let i = 0; i < topics.length; i++){
          if (topics[i].id !== id){
            newTopics.push(topics[i]);
          }
        }
        setTopics(newTopics);
        setMode('WELCOME');
      }}/></li>
    </>
  }
}
반응형

'programming > web' 카테고리의 다른 글

[Error] TypeError: destroy is not a function  (0) 2023.02.25
[Error] next.js에서 caver-js 에러  (0) 2023.02.24
.htaccess  (0) 2023.02.06
NVM  (0) 2023.02.05
package-lock.json  (0) 2023.02.05