본문 바로가기
Research/React

React_Form submission

by RIEM 2023. 4. 24.

React

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';

import './index.css';

const books = [
  {
    author: 'Charles Dickens',
    title: 'Interesting Topics',
    img: './images/book-1.jpg',
    id: 1,
  },
  {
    author: 'Laura Dave',
    title: 'The Last Thing He Told Me',
    img: './images/book-2.jpg',
    id: 2,
  },
];

const BookList = () => {
  return (
    <section className='booklist'>
      <EventExamples />
      {books.map((book) => {
        return <Book {...book} key={book.id} />;
      })}
    </section>
  );
};

const EventExamples = () => {
  const handleFormInput = (e) => {
    console.log(e.target);
    console.log(e.target.name);
    console.log(e.target.value);
    console.log('handle form input!!');
  };
  const handleButtonClick = () => {
    alert('handle button clicked!! :D');
  };
  const handleFormSubmission = (e) => {
    // avoid re-rendering
    e.preventDefault();
    console.log('You subbable submission');
  };
  return (
    <section>
      <form onSubmit={handleFormSubmission}>
        <h2>Typical Form</h2>
        <input
          type='text'
          name='example'
          onChange={handleFormInput}
          style={{ margin: '1rem' }}
        />
      </form>
      <button onClick={handleButtonClick}>Click Me</button>
    </section>
  );
};

const Book = (props) => {
  const { img, title, author, children } = props;
  return (
    <article>
      {/* Dynamically render title */}
      <img src={img} alt={title} />
      <h2>{title}</h2>
      <h4>{author}</h4>
      {children}
    </article>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<BookList />);

댓글