카테고리 없음

React Basic CRUD

meta-tony 2023. 3. 16. 13:12

 

Handwriting
event & prop(Read)Create / Update

React Basic CRUD 10 step (Reference 생활코딩)

1. Install
nodejs
create-react-app
2. Edit
react file root (start frame) CSS, root, 
"." 은 현재 디렉토리
3. 배포 distribute
(yarn) build : build fold 생성
(yarn) global add serve 
(npx) serve -s build : build 서브 배포
4. 사용자 정의 태그 component
코드를 더욱 직관적으로 만들 수 있다.
첫글자는 대문자를 입력하고 리턴값은 하나의 태그로 감싸져야한다. (fragment; <></> 복수의 태그 그룹핑)
*COMPONENT Definition
Noun; a part or element of a larger whole, especially a part of a machine or vehicle.
Adjective; constituting part of a larger whole; constituent.
5. props
{}를 통한 표현식 사용 및 prop 전달
컴포넌트 함수의 파라미터는 컴포넌트 태그를 렌더
배열 객체 반복문 사용하여 출력(map, for) , 추적을 위한 key값
6. event
JSX 속성 문법 카멜기법(띄어쓰기 대신 대문자 사용)
컴포넌트 onChange 이벤트 태그 onClick 에서props.onChangeMode() 트리거 및 reload 방지(preventDefault)
target을 통한 id값 호출하기
7. state
문자열을 통한 조건문 작성 - READ
React Hook - useState 구성
useState 함수 배열의 파라미터 구성 (0: 초기값-읽기, 1:함수-변경)
const [state, setState] = useState('초기값')
배열과 클릭 태그 id가 일치하는 JSON 출력 - 태그의 속성은 문자열 Number()를 통한 변환
8.Create
문자열 조건문을 통한 입력창 <form> 작성, submit 이 실행될 때 렌더 되는 함수 onSubmit 사용 후 onCreate 전달
props는 입력 변경이 불가 state로 승격
state는 동일한 값은 메모리 누수로 인해 렌더하지 않음. 
복사본 변경 후 원본에 입력(스프래드연산자  https://bbangson.tistory.com/78 ) 
작업 완료 후 상태 변경(READ)
9. Update
CREATE와 동일한 구조의 <form>
조건문 "READ"  만 출력
기존의 내용 출력(READ 조건문과 동일)
props는 입력하여 변경 불가 state로 승격
state의 초기값을 가져온 props로 구성
onChange()의 타겟으로 state변경
수정된 JSON 작성 후 복제한 배열에 변경 후 state 변경 후 조건문 READ 실행
10. Delete
빈 배열에 선택된 태그와  id가 다른 값만 추가 후 state 변경 후 모드 조건문 설정

완성코드(비구조할당, 삼항연산자, map(), switch문 사용)

더보기
import React,{useState} from "react"
import "./App.css"
const Header = props => {
return(
  <>
  <h1><a href="./" onClick={e=>{
    e.preventDefault();
    props.onChangeMode()
  }}>{props.title}</a></h1>
  </>
)
}
const Nav = props => {
  let t = props.topics;
  let lis = t.map(item => {
      return(
      <li key={item.id}>
        <a href={"/"+t.id} onClick={e=>{
          e.preventDefault()
          props.onChangeMode(item.id)
        }}>
          {item.title}
        </a>
      </li>)
  })
return(
  <>
    <ol>
      {lis}
    </ol>
  </>
)
}
const Article = props => {
return(
  <article>
    <h2>{props.title}</h2>
    <p>{props.body}</p>
  </article>
)
}
const Create = (props) => {
  let title, body = null
  return(
    <div>
      <h2>Create</h2>
        <form onSubmit={(e)=>{
          e.preventDefault();
          title = e.target.title.value
          body = e.target.body.value
          props.onCreate(title, body)
        }}>
          <p><input type="text" name="title" placeholder="Program Name" /></p>
          <p><textarea name="body" placeholder="Explanation" /></p>
          <input type="submit" value="Create"/>
        </form>
    </div>
  )
}
const Update = (props) => {
  let [title, setTitle] = useState(props.title)
  let [body, setBody] = useState(props.body)
  return(
    <div>
      <h2>Update</h2>
        <form onSubmit={(e)=>{
          e.preventDefault();
          props.onUpdate(title, body)
        }}>
          <p><input type="text" name="title" placeholder="Program Name" value={title} onChange={e=>{
            setTitle(e.target.value)
          }}/></p>
          <p><textarea name="body" placeholder="Explanation" value={body} onChange={e=>{
            setBody(e.target.value)
          }}/></p>
          <input type="submit" value="Update"/>
        </form>
    </div>
  )  
}
const App = () => {
  const [topics, setTopics] = useState([
    {id:1, title:'HTML', body:'HTML is ...'},
    {id:2, title:'CSS', body:'CSS is ...'},
    {id:3, title:'Javascript', body:'Javascript is ...'}
  ])
  const [mode, setMode] =useState('WELCOME')
  const [id, setId] = useState(1)
  const [nextId, setNextId] = useState(4)

  let content = null;
  let body, title = null
  let newTopic, newTopics = null;
  let control = null;

  switch (mode){
    case 'READ':
    topics.map(item=> {
      if(id === item.id ) {
        title = item.title;
        body = item.body;        
      }
    })

      content = <Article title={title} body={body}/>
      control = 
      <>
        <li>
          <a href="/create" onClick={e=>{
            e.preventDefault()
            setMode('CREATE')
          }}>Create</a>
        </li>
        <li>
          <a href="/update" onClick={e=>{
            e.preventDefault()
            setMode('UPDATE')
          }}>Update</a>
        </li>
        <li>
          <button onClick={()=> {
            newTopics = topics.filter(item => item.id !== id)
            setTopics(newTopics)
            setMode('WELCOME')
          }}>Delete</button>
        </li>
      </>
      break;
    case 'CREATE':
      content = <Create onCreate={(title, body)=>{
        newTopic = {id:nextId, title:title, body:body}
        newTopics = [...topics]
        newTopics.push(newTopic)
        setTopics(newTopics)
        setId(nextId)
        setNextId(nextId+1)
        setMode('READ')
      }}/>      
      break;
    case 'UPDATE': 
      let updatedTopics = topics.filter(itme => id === itme.id)
        .map(item => {return(title=item.title, body=item.body)})
      content = <Update title={title} body={body} onUpdate={(title, body)=>{
        updatedTopics= topics.map(item => id === item.id ? {id:id, title:title, body:body} : item )
        setTopics(updatedTopics)
        setMode('READ')
      }}/>
      break;
    default: 
      content = <Article title={'Welcome'} body={"Web Development Industrial"}/>
      control = 
      <li>
        <a href="/create" onClick={e=>{
          e.preventDefault()
          setMode('CREATE')
        }}>Create</a>
      </li>
  }
  return (
    <div>
      <Header title={'WEB'} onChangeMode={()=>{
        setMode('WELCOME')
      }} />
      <Nav topics={topics} onChangeMode={(id)=>{
        setId(id)
        setMode('READ')
      }}/>
      {content}
      <ul>
        {control}
      </ul>
    </div>
  );
}

export default App;

기존코드 (For문, If문 사용)

더보기
import React,{useState} from "react"
const Header = props => {
return(
  <>
  <h1><a href="./" onClick={e=>{
    e.preventDefault();
    props.onChangeMode()
  }}>{props.title}</a></h1>
  </>
)
}
const Nav = props => {
  let t = props.topics;
  let lis = [];
  for(let i=0; i<t.length; i++) {
    lis.push(
      <li key={t[i].id}>
        <a href={"/"+t.id} onClick={e=>{
          e.preventDefault()
          props.onChangeMode(t[i].id)
        }}>
          {t[i].title}
        </a>
      </li>
    )
  }
return(
  <>
    <ol>
      {lis}
    </ol>
  </>
)
}
const Article = props => {
return(
  <article>
    <h2>{props.title}</h2>
    <p>{props.body}</p>
  </article>
)
}
const Create = (props) => {
  let title, body = null
  return(
    <div>
      <h2>Create</h2>
        <form onSubmit={(e)=>{
          e.preventDefault();
          title = e.target.title.value
          body = e.target.body.value
          props.onCreate(title, body)
        }}>
          <p><input type="text" name="title" placeholder="Program Name" /></p>
          <p><textarea name="body" placeholder="Explanation" /></p>
          <input type="submit" value="Create"/>
        </form>
    </div>
  )
}
const Update = (props) => {
  let [title, setTitle] = useState(props.title)
  let [body, setBody] = useState(props.body)
  return(
    <div>
      <h2>Update</h2>
        <form onSubmit={(e)=>{
          e.preventDefault();
          props.onUpdate(title, body)
        }}>
          <p><input type="text" name="title" placeholder="Program Name" value={title} onChange={e=>{
            setTitle(e.target.value)
          }}/></p>
          <p><textarea name="body" placeholder="Explanation" value={body} onChange={e=>{
            setBody(e.target.value)
          }}/></p>
          <input type="submit" value="Update"/>
        </form>
    </div>
  )  
}
const App = () => {
  const [topics, setTopics] = useState([
    {id:1, title:'HTML', body:'HTML is ...'},
    {id:2, title:'CSS', body:'CSS is ...'},
    {id:3, title:'Javascript', body:'Javascript is ...'}
  ])
  const [mode, setMode] =useState('WELCOME')
  const [id, setId] = useState(1)
  const [nextId, setNextId] = useState(4)

  let content = null;
  let body, title = null
  let newTopic, newTopics = null;
  let ctrl = null;

  if(mode === 'WELCOME') {
    content = <Article title={'Welcome'} body={"Web Development Industrial"}/>
  }else if(mode === 'READ') {
    for(let i=0; i<topics.length; i++) {
      if(id === topics[i].id) {
        title = topics[i].title;
        body = topics[i].body;
        break;
      }
    }
    content = <Article title={title} body={body}/>
    ctrl = 
    <>
      <li>
        <a href="/update" onClick={e=>{
          e.preventDefault()
          setMode('UPDATE')
        }}>Update</a>
      </li>
      <li>
        <button onClick={()=> {
          newTopics = []
          for(let i=0; i<topics.length; i++) {
            if(topics[i].id !== id) {
              newTopics.push(topics[i])
            }
          }
          setTopics(newTopics)
          setMode('WELCOME')
        }}>Delete</button>
      </li>
    </>
  }else if(mode === 'CREATE') {
    content = <Create onCreate={(title, body)=>{
      newTopic = {id:nextId, title:title, body:body}
      newTopics = [...topics]
      newTopics.push(newTopic)
      setTopics(newTopics)
      setId(nextId)
      setNextId(nextId+1)
      setMode('READ')
    }}/>
  }else if(mode === 'UPDATE') {
    let updatedTopics = [];
    for(let i=0; i<topics.length; i++) {
      if(id === topics[i].id) {
        title = topics[i].title;
        body = topics[i].body;
        break;
      }
    }
    content = <Update title={title} body={body} onUpdate={(title, body)=>{
      for(let i=0; i<topics.length; i++){ 
        if(id === topics[i].id){
          updatedTopics.push({id:id, title:title, body:body})
        }else{
          updatedTopics.push(topics[i])
        }
      }
      setTopics(updatedTopics)
      setMode('READ')
    }}/>
  }
  return (
    <div>
      <Header title={'WEB'} onChangeMode={()=>{
        setMode('WELCOME')
      }} />
      <Nav topics={topics} onChangeMode={(id)=>{
        setId(id)
        setMode('READ')
      }}/>
      {content}
      <ul>
        <li>
          <a href="/create" onClick={e=>{
            e.preventDefault()
            setMode('CREATE')
          }}>Create</a>
        </li>
        {ctrl}
      </ul>
    </div>
  );
}

export default App;



https://meta-tony.tistory.com/m/50

React-Ajax

React를 통한 간단한 AJAX 코드//fetch호출이 시작되는 public폴더에 list.json과 1, 2, 3 파일명의 json을 저장 class Nav extends Component { state = { list:[] } componentDidMount() { fetch('list.json') .then(function(result){ return re

meta-tony.tistory.com