Certainly! Below is a simple example of how to create a React application that interacts with a Strapi backend to upload images and create a post with user relation. This example assumes you have your Strapi project set up as described earlier and your content types created.
Step 1: Create a React App
First, create a new React application if you don’t have one:
npx create-react-app my-strapi-app
cd my-strapi-app
npm start
Step 2: Install Axios
You'll need Axios for making API requests. Install it by running:
npm install axios
Step 3: Create Components
Create a component to handle image uploads and post creation, e.g., PostForm.js.
// src/PostForm.js
import React, { useState } from 'react';
import axios from 'axios';
const PostForm = () => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [image, setImage] = useState(null);
const [authorId, setAuthorId] = useState(''); // Change this to the logged-in user's ID
const handleImageChange = (e) => {
setImage(e.target.files[0]);
};
const handleSubmit = async (e) => {
e.preventDefault();
// Upload image
let uploadedImageId = '';
if (image) {
const formData = new FormData();
formData.append('files', image);
try {
const uploadResponse = await axios.post('http://localhost:1337/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
uploadedImageId = uploadResponse.data[0].id; // Get the ID of the uploaded image
} catch (err) {
console.error('Image upload failed: ', err);
}
}
// Create post
const postData = {
data: {
title,
content,
image: uploadedImageId ? [{ id: uploadedImageId }] : [],
author: authorId,
},
};
try {
await axios.post('http://localhost:1337/api/posts', postData);
alert('Post created successfully!');
} catch (error) {
console.error('Error creating post: ', error);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Title:</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
<div>
<label>Content:</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
required
/>
</div>
<div>
<label>Image:</label>
<input
type="file"
onChange={handleImageChange}
required
/>
</div>
<div>
<label>Author ID:</label>
<input
type="text"
value={authorId}
onChange={(e) => setAuthorId(e.target.value)}
required
/>
</div>
<button type="submit">Create Post</button>
</form>
);
};
export default PostForm;
Step 4: Use the Component
You can now use the PostForm component in your App.js:
// src/App.js
import React from 'react';
import PostForm from './PostForm';
const App = () => {
return (
<div className="App">
<h1>Create a New Post</h1>
<PostForm />
</div>
);
};
export default App;
Step 5: Run Your React App
Make sure your Strapi server is running, and then start your React app:
npm start
Step 6: Test the Form
Navigate to http://localhost:3000 in your web browser. You should see a form where you can input a title, content, select an image, and specify the author ID. Once submitted, it should upload the image to Strapi, create a new post, and relate it to the specified user.
Notes
- Ensure that the author ID you provide corresponds to a valid user ID in your Strapi database.
- You might want to manage user authentication and fetch the logged-in user's ID dynamically, which is not included in this simple example.
- You can further enhance the error handling and UX by adding loading states, success/failure notifications, or form validations.