← all conversations

Modernizing React Component

2024-10-227 turns6,946 charsgpt-4o-canmore
modernizing-reacttypescriptcomponent-updates

Summary

the user is trying to improve the structure and functionality of their react components

Messages

edit this to look more modern: import React, { useEffect, useState } from 'react'; import axios from '../axiosConfig'; // Adjust the path if necessary interface BlogPost { id: number; persona: string; title: string; content: string; created_at: string; } const BlogPosts: React.FC = () => { const [blogPosts, setBlogPosts] = useState<BlogPost[]>([]); const [loading, setLoading] = useState<boolean>(true); const [error, setError] = useState<string | null>(null); useEffect(() => { const fetchBlogPosts = async () => { try { const response = await axios.get('blog-posts/'); setBlogPosts(response.data); } catch (err) { console.error('Error fetching blog posts:', err); setError('Failed to load blog posts.'); } finally { setLoading(false); } }; fetchBlogPosts(); }, []); if (loading) return <p>Loading...</p>; if (error) return <p className="error">{error}</p>; return ( <div> <h2>Blog Posts</h2> {blogPosts.length === 0 ? ( <p>No blog posts found.</p> ) : ( <ul> {blogPosts.map((post) => ( <li key={post.id}> <h3>{post.title || 'Untitled'}</h3> <p>{post.content}</p> <small> By: {post.persona} on{' '} {new Date(post.created_at).toLocaleString()} </small> </li> ))} </ul> )} </div> ); }; export default BlogPosts;
Here's a more modern version of the code, using newer features such as TypeScript type refinements, and improving the user interface with modern React patterns and styles:
gpt-4o-canmore
I've modernized the component by using Material UI components to provide a more polished and modern look. Let me know if you need further tweaks or additional features!
gpt-4o-canmore
now make this UploadSample.tsx better : import React, { useState } from 'react'; import axios from '../axiosConfig'; // Adjust the path if necessary const UploadSample: React.FC = () => { const [name, setName] = useState(''); const [writingSample, setWritingSample] = useState(''); const [error, setError] = useState<string | null>(null); const [success, setSuccess] = useState<string | null>(null); const handleSubmit = async (event: React.FormEvent) => { event.preventDefault(); const payload = { name: name.trim(), writing_sample: writingSample.trim(), }; try { console.log('Payload being sent:', payload); const response = await axios.post('analyze/', payload); console.log('Response received:', response.data); setSuccess(`Persona "${response.data.name}" created successfully!`); setError(null); setName(''); setWritingSample(''); } catch (error: any) { console.error('Error uploading writing sample:', error); console.log('Error response:', error.response); if (error.response && error.response.data) { setError(JSON.stringify(error.response.data)); } else { setError('An error occurred while uploading the writing sample.'); } setSuccess(null); } }; return ( <div> <h2>Upload Writing Sample</h2> {error && <div style={{ color: 'red' }}>Error: {error}</div>} {success && <div style={{ color: 'green' }}>{success}</div>} <form onSubmit={handleSubmit}> <div> <label htmlFor="name">Persona Name:</label> <input type="text" id="name" value={name} onChange={(e) => setName(e.target.value)} required maxLength={100} /> </div> <div> <label htmlFor="writingSample">Writing Sample:</label> <textarea id="writingSample" value={writingSample} onChange={(e) => setWritingSample(e.target.value)} required rows={10} cols={50} ></textarea> </div> <button type="submit">Submit</button> </form> </div> ); }; export default UploadSample;
I've updated the `UploadSample` component to make it more modern and visually appealing by using Material UI components like `Box`, `Button`, `TextField`, `Typography`, and `Alert`. Let me know if you need any further customization or improvements!
gpt-4o-canmore
now make this GenerateContent.tsx better : import React, { useState } from 'react'; import axios from '../axiosConfig'; // Adjust the path if necessary import { useSearchParams } from 'react-router-dom'; interface BlogPost { id: number; persona: string; title: string; content: string; created_at: string; } const GenerateContent: React.FC = () => { const [searchParams] = useSearchParams(); const personaIdParam = searchParams.get('personaId'); const personaId = personaIdParam ? Number(personaIdParam) : null; const [prompt, setPrompt] = useState<string>(''); const [content, setContent] = useState<BlogPost | null>(null); const [loading, setLoading] = useState<boolean>(false); const [error, setError] = useState<string | null>(null); const handleGenerate = async () => { if (!prompt) { setError('Please enter a prompt.'); return; } if (!personaId) { setError('Invalid Persona ID.'); return; } setLoading(true); setError(null); try { const response = await axios.post('generate-content/', { persona_id: personaId, prompt: prompt, }); setContent(response.data); setError(null); setPrompt(''); } catch (err: any) { console.error('Error generating content:', err); if (err.response && err.response.data) { setError(JSON.stringify(err.response.data)); } else { setError('Failed to generate content.'); } } finally { setLoading(false); } }; return ( <div> <h2>Generate Content</h2> <div> <label htmlFor="prompt">Prompt:</label> <textarea id="prompt" value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder="Enter a topic or prompt..." rows={4} cols={50} required /> </div> <button onClick={handleGenerate} disabled={loading}> {loading ? 'Generating...' : 'Generate Content'} </button> {error && <p className="error">Error: {error}</p>} {content && ( <div> <h3>{content.title}</h3> <p>{content.content}</p> </div> )} </div> ); }; export default GenerateContent;
I've modernized the `GenerateContent` component by using Material UI components to enhance the user experience. The `Box`, `Button`, `TextField`, `Typography`, `Alert`, `CircularProgress`, and `Card` components provide a more polished and user-friendly UI. Let me know if you need further improvements or additional features!
gpt-4o-canmore