Adjusting the CreatePost component

Next, we need to use the setPosts function in order to insert a new post, when we press the Create button.

Let's start modifying the CreatePost component in order to make it dynamic:

  1. Edit src/posts/CreatePost.js, and import the useState Hook:
import React, { useState } from 'react'
  1. Then, adjust the function definition to accept the posts and setPosts props:
export default function CreatePost ({ user, posts, setPosts }) {
  1. Next, we define two new State Hooks—one for the title value, and one for the content value:
    const [ title, setTitle ] = useState('')
const [ content, setContent ] = useState('')
  1. Now, we define two handler functions—one for the input field, and one for the textarea:
    function handleTitle (evt) {
setTitle(evt.target.value)
}

function handleContent (evt) {
setContent(evt.target.value)
}
  1. We also define a handler function for the Create button:
    function handleCreate () {
  1. In this function, we first create a newPost object from the input field values:
        const newPost = { title, content, author: user }
In newer JavaScript versions, we can shorten the following object assignment: { title: title }, to { title }, and it will have the same effect. So, instead of doing { title: title, contents: contents }, we can simply do { title, contents }.
  1. Then, we set the new posts array by first adding newPost to the array, then using the spread syntax to list all of the existing posts:
        setPosts([ newPost, ...posts ])
}
  1. Next, we add the value and handler functions to the input field and textarea element:
             <div>
<label htmlFor="create-title">Title:</label>
<input type="text" value={title} onChange={handleTitle} name="create-title"
id="create-title" />
</div>
<textarea value={content} onChange={handleContent} />
Usually in HTML, we put the value of textarea as its children. However, in React, textarea can be handled like any other input field, by using the value and onChange props.
  1. Finally, we pass the handleCreate function to the onSubmit handler of the form element:
         <form onSubmit={e => { e.preventDefault(); handleCreate() }}>
  1. Now, we can log in and create a new post, and it will be inserted at the beginning of the feed:

Our first version of the blog app using Hooks, after inserting a new blog post

As we can see, now our application is fully dynamic, and we can use all of its features!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.217.134