Reputation: 21
i would like to know how to create a comment section using react typescript, I would like the user to put a name and there comment, which is then sent to my firebase project. i would also like if the comments made can be showed right below the comment form, the code below is all I have manage to do, how do I approach this please
import React, { EventHandler, FormEventHandler, useState, FC } from 'react'
import { Box, Button, Grid, TextField } from '@material-ui/core';
import axios from "axios";
interface FormData {
user: string;
comment: string;
}
const Comment: FC<FormData> = ({}) => {
const [formData, setFormData] = useState({ user: "", comment: ""})
const handleChange = (e) => {
const { value, name } = e.target;
setFormData({ ...formData, [name]: value })
console.log(formData)
}
const handleSubmit = async (e) => {
e.preventDefault();
const response = await axios.post('/api/comments/index', formData);
}
return (
<Box component="form"
my={3}
>
<Grid container
direction="row"
justify="center"
alignItems="flex-end"
spacing={2}
>
<Grid item xs={6}>
<TextField id="outlined-basic" label="Firstname" variant="outlined" name="firstname" onChange={handleChange} />
</Grid>
<Grid item xs={6}>
<TextField
id="filled-multiline-static"
label="Comment"
multiline
rows={4}
defaultValue="Share with your artist "
variant="filled" onChange={handleChange}/>
</Grid>
<Box mt={5} display="flex" justifyContent="center">
<Box width="70%">
<Button type="submit" variant="contained" color="primary" fullWidth onClick={handleSubmit}>Add Comment</Button>
</Box>
</Box>
</Grid>
</Box>
)
}
export default Comment
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Upvotes: 0
Views: 1010
Reputation: 1074268
Two issues:
useState
correctlyundefined
useState
returns a tuple (array) with two elements:
Your code:
const [SetPlayingCurrentSong] = useState()
const [playingCurrentSong] = useState()
...is only using the first. Your current code is creating and getting the current state of two state members, not one. It should be one useState
call using both elements from the returned tuple:
const [playingCurrentSong, SetPlayingCurrentSong] = useState()
playingCurrentSong
will get the current value of the state member, and SetPlayingCurrentSong
will get the setter for that state member.
If you want an initial value other than undefined
, pass that value into useState
:
const [playingCurrentSong, SetPlayingCurrentSong] = useState(theInitialValue)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^
Side note: Although you can do whatever you like in your own code, the overwhelmingly common convention in JavaScript is that only cosntructor functions are initially-capped. SetPlayingCurrentSong
should be setPlayingCurrentSong
(lower case initial "s").
Upvotes: 5