Home > Software design >  When using useState I get "Failed to compile" "not defined" with React and Mater
When using useState I get "Failed to compile" "not defined" with React and Mater

Time:10-17

For this project I am building a component to create a blog post. I am not sure why I am getting this message. I have tried placing the useState piece of code outside the function but I am getting even more errors. I think I have imported { useState } correctly.

import * as React from 'react';
import { useState } from 'react';
import { TextField, Typography, Button, FormControl, FormControlLabel, Radio } from "@mui/material";
import { Container } from "@mui/system";

const PostForm = () => {

const submitClick = (e) => {
    e.preventDefault();
    const blog = { title, content, category };

const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [category, setCategory] = useState('');

fetch('http://localhost:8000/posts/', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(blog)
})
.then (() => {
    console.log('post added successfully');
})
}

return(
    <Container maxWidth="lg">
        <Typography variant="h5">Create a post</Typography>
            <form onSubmit={submitClick}>
                <TextField label="Post title" variant="outlined" value={title} onChange={(e) => setTitle(e.target.value)} fullWidth required />
                <TextField label="Post content" variant="outlined" multiline minRows={5} value={content} onChange={(e) => setContent(e.target.value)} fullWidth required />
                    <Typography>
                        <TextField label="Image URL" variant="outlined" sx={{ width: "100%" }} required />
                    </Typography>
                <Typography variant="h6">Category</Typography>
                    <FormControl>
                        <FormControlLabel control={<Radio />} label="News" />
                        <FormControlLabel control={<Radio />} label="Sports" />
                        <FormControlLabel control={<Radio />} label="Finance" />
                    </FormControl>
                <Button type="submit" variant="contained" sx={{ display: "block" }}>Submit</Button>
            </form>
    </Container>
);
}

export default PostForm;

./src/components/PostForm.jsx Line 30: 'title' is not defined no-undef Line 30: 'setTitle' is not defined no-undef Line 31: 'content' is not defined no-undef Line 31: 'setContent' is not defined no-undef

Search for the keywords to learn more about each error.

CodePudding user response:

you have define the variable inside the function. need to define it in the component level

const PostForm = () => {
 

const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [category, setCategory] = useState('');

const submitClick = (e) => {

    
    const blog = { title, content, category };
    e.preventDefault(); 
....
  • Related