본문 바로가기

Dev/React

리액트 react create

예제

function Article(props) {
  return <article>
  <h2>{props.title}</h2>
  {props.body}
</article>
}
function Header(props) {
  return <header>
  <h1><a href="/" onClick={(event)=>{
    event.preventDefault(); // 기본 동작 방지
    props.onChangeMod();
  }}>{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 id={t.id} href={'/read/'+t.id} onClick={event=>{
        event.preventDefault();
        props.onChangeMod(Number(event.target.id));
      }}>{t.title}</a>
      </li>);
  }
  return <nav>
  <ol>
    {lis}
  </ol>
</nav>
}
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"/></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:'javascript', 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>
  } else 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" onChangeMod={()=>{
        setMode('WELCOME');
      }}></Header>
      <Nav topics={topics} onChangeMod={(_id)=>{
        setMode('READ');
        setId(_id);
      }}></Nav>
      {content}
      <a href="/create" onClick={event=>{
        event.preventDefault();
        setMode('CREATE');
      }}>Create</a>
    </div>
  );
}

export default App;

 

결과

 

풀이

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

App 컴포넌트에 Create라는 a태그를 눌렀을때 페이지 리로드가 일어나지 않기 위해 event.preventDefault(); 사용

Create라는 a태그를 눌렀을때 mode의 값을 setMode를 통해 CREATE 상태로 변경

  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:'javascript', body:'javascript is ...'}
  ])
  let content = null;
else 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>
  }

mode 의 값의 CREATE라면 </Create> 컴포넌트 실행

_title, _body를 받는 onCreate 함수를 정의

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"/></p>
    </form>
  </article>
}

submit 버튼을 눌렀을때 페이지 리로드가 일어나지 않기 위해 event.preventDefault(); 사용

title, body 변수에 event.target.(name).value로 작성된 값을 담음

props를 통해 onCreate함수 실행

    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>

newTopic에 작성한 값을 담음

newTopics에 topics의 값을 복제

복제한 값에 생성한 newTopic의 정보를 담음

setTopics(newTopics)를 통해 기존의 값과 복제된 값을 비교하여 달라졌기 때문에 새로 렌더링함

setId(nextId)를 통해 id를 부여해줌

setNextId(nextId+1)를 통해 다음에 생성될 id값을 생성해줌

'Dev > React' 카테고리의 다른 글

리액트 react state  (1) 2023.11.12
리액트 react 이벤트(event)  (0) 2023.11.11
리액트 react 속성(props)  (0) 2023.11.11
리액트 react 컴포넌트 만들기  (0) 2023.11.11
리액트 react 소스 수정 방법, 배포  (0) 2023.11.11