I'll help you create a more comprehensive X clone with additional features. Let's break it down into key components and features. This will be Part 1 of the implementation, focusing on core UI components and basic functionality.
First, let's set up the project with necessary dependencies:
npx create-react-app x-clone --template typescript
cd x-clone
npm install @heroicons/react @headlessui/react
npm install @tailwindcss/forms
npm install firebase
npm install recoil
npm install react-router-dom
npm install date-fns
Here's the enhanced implementation:
- First, let's create our types (src/types/index.ts):
export interface Tweet {
id: string;
text: string;
userId: string;
timestamp: any;
image?: string;
likes: string[];
retweets: string[];
replies: string[];
quoteTweets: string[];
}
export interface User {
id: string;
name: string;
username: string;
email: string;
profileImage?: string;
coverImage?: string;
bio?: string;
location?: string;
website?: string;
followers: string[];
following: string[];
createdAt: any;
verified: boolean;
}
- Create the main layout (src/components/Layout/MainLayout.tsx):
import React from 'react';
import Sidebar from '../Sidebar/Sidebar';
import Widgets from '../Widgets/Widgets';
import { useRecoilValue } from 'recoil';
import { modalState } from '../../atoms/modalAtom';
import Modal from '../Modal/Modal';
interface MainLayoutProps {
children: React.ReactNode;
}
const MainLayout: React.FC<MainLayoutProps> = ({ children }) => {
const isModalOpen = useRecoilValue(modalState);
return (
<div className="min-h-screen bg-black">
<div className="max-w-[1500px] mx-auto flex">
<Sidebar />
<main className="flex-grow border-l border-r border-gray-700 max-w-2xl sm:ml-[73px] xl:ml-[370px]">
{children}
</main>
<Widgets />
</div>
{isModalOpen && <Modal />}
</div>
);
};
export default MainLayout;
- Create the Sidebar component (src/components/Sidebar/Sidebar.tsx):
import React from 'react';
import { useNavigate } from 'react-router-dom';
import {
HomeIcon,
HashtagIcon,
BellIcon,
InboxIcon,
BookmarkIcon,
ClipboardListIcon,
UserIcon,
DotsCircleHorizontalIcon,
} from '@heroicons/react/outline';
import SidebarLink from './SidebarLink';
import { useRecoilState } from 'recoil';
import { modalState } from '../../atoms/modalAtom';
const Sidebar = () => {
const navigate = useNavigate();
const [, setIsModalOpen] = useRecoilState(modalState);
return (
<div className="hidden sm:flex flex-col items-center xl:items-start xl:w-[340px] p-2 fixed h-full">
<div className="flex items-center justify-center w-14 h-14 hoverAnimation p-0 xl:ml-24">
<img src="/x-logo.svg" alt="X Logo" className="w-8 h-8" />
</div>
<div className="space-y-2.5 mt-4 mb-2.5 xl:ml-24">
<SidebarLink text="Home" Icon={HomeIcon} active />
<SidebarLink text="Explore" Icon={HashtagIcon} />
<SidebarLink text="Notifications" Icon={BellIcon} />
<SidebarLink text="Messages" Icon={InboxIcon} />
<SidebarLink text="Bookmarks" Icon={BookmarkIcon} />
<SidebarLink text="Lists" Icon={ClipboardListIcon} />
<SidebarLink text="Profile" Icon={UserIcon} />
<SidebarLink text="More" Icon={DotsCircleHorizontalIcon} />
</div>
<button
className="hidden xl:inline ml-auto bg-[#1d9bf0] text-white rounded-full w-56 h-[52px] text-lg font-bold shadow-md hover:bg-[#1a8cd8]"
onClick={() => setIsModalOpen(true)}
>
Post
</button>
<div
className="text-[#d9d9d9] flex items-center justify-center mt-auto hoverAnimation xl:ml-auto xl:-mr-5"
onClick={() => navigate('/profile')}
>
<img
src={user?.profileImage || "/default-avatar.png"}
alt=""
className="h-10 w-10 rounded-full xl:mr-2.5"
/>
<div className="hidden xl:inline leading-5">
<h4 className="font-bold">{user?.name}</h4>
<p className="text-[#6e767d]">@{user?.username}</p>
</div>
<DotsCircleHorizontalIcon className="h-5 hidden xl:inline ml-10" />
</div>
</div>
);
};
export default Sidebar;
- Create the Feed component (src/components/Feed/Feed.tsx):
import React, { useEffect, useState } from 'react';
import { SparklesIcon } from '@heroicons/react/outline';
import Input from './Input';
import Tweet from './Tweet';
import { db } from '../../firebase';
import { collection, onSnapshot, orderBy, query } from 'firebase/firestore';
import { Tweet as TweetType } from '../../types';
const Feed = () => {
const [tweets, setTweets] = useState<TweetType[]>([]);
useEffect(() => {
const unsubscribe = onSnapshot(
query(collection(db, "tweets"), orderBy("timestamp", "desc")),
(snapshot) => {
setTweets(snapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
} as TweetType)));
}
);
return () => unsubscribe();
}, []);
return (
<div className="text-white flex-grow border-l border-r border-gray-700 max-w-2xl sm:ml-[73px] xl:ml-[370px]">
<div className="text-[#d9d9d9] flex items-center sm:justify-between py-2 px-3 sticky top-0 z-50 bg-black border-b border-gray-700">
<h2 className="text-lg sm:text-xl font-bold">Home</h2>
<div className="hoverAnimation w-9 h-9 flex items-center justify-center xl:px-0 ml-auto">
<SparklesIcon className="h-5 text-white" />
</div>
</div>
<Input />
<div className="pb-72">
{tweets.map(tweet => (
<Tweet key={tweet.id} tweet={tweet} />
))}
</div>
</div>
);
};
export default Feed;
- Create the Tweet component (src/components/Feed/Tweet.tsx):
import React, { useState } from 'react';
import {
ChartBarIcon,
ChatIcon,
HeartIcon,
ShareIcon,
SwitchHorizontalIcon,
} from '@heroicons/react/outline';
import { HeartIcon as HeartIconFilled } from '@heroicons/react/solid';
import { Tweet as TweetType } from '../../types';
import { formatDistanceToNowStrict } from 'date-fns';
import { useNavigate } from 'react-router-dom';
interface TweetProps {
tweet: TweetType;
}
const Tweet: React.FC<TweetProps> = ({ tweet }) => {
const [liked, setLiked] = useState(false);
const [likes, setLikes] = useState(tweet.likes.length);
const navigate = useNavigate();
const handleLike = async (e: React.MouseEvent) => {
e.stopPropagation();
// Implement like functionality
setLiked(!liked);
setLikes(liked ? likes - 1 : likes + 1);
};
return (
<div
className="p-3 flex cursor-pointer border-b border-gray-700"
onClick={() => navigate(`/tweet/${tweet.id}`)}
>
<img
src={tweet.user?.profileImage || "/default-avatar.png"}
alt=""
className="h-11 w-11 rounded-full mr-4"
/>
<div className="flex flex-col space-y-2 w-full">
<div className="flex justify-between">
<div className="text-[#6e767d]">
<div className="inline-block group">
<h4 className="font-bold text-[#d9d9d9] text-[15px] sm:text-base inline-block group-hover:underline">
{tweet.user?.name}
</h4>
<span className="ml-1.5 text-sm sm:text-[15px]">
@{tweet.user?.username}
</span>
</div>
·{" "}
<span className="hover:underline text-sm sm:text-[15px]">
{formatDistanceToNowStrict(tweet.timestamp?.toDate())}
</span>
<p className="text-[#d9d9d9] mt-0.5 max-w-lg text-[15px] sm:text-base">
{tweet.text}
</p>
</div>
</div>
{tweet.image && (
<img
src={tweet.image}
alt=""
className="rounded-2xl max-h-[700px] object-cover mr-2"
/>
)}
<div className="flex justify-between w-10/12 text-[#6e767d]">
<div className="flex items-center space-x-1 group">
<div className="icon group-hover:bg-[#1d9bf0] group-hover:bg-opacity-10">
<ChatIcon className="h-5 group-hover:text-[#1d9bf0]" />
</div>
{tweet.replies.length > 0 && (
<span className="group-hover:text-[#1d9bf0] text-sm">
{tweet.replies.length}
</span>
)}
</div>
<div className="flex items-center space-x-1 group">
<div className="icon group-hover:bg-green-500/10">
<SwitchHorizontalIcon className="h-5 group-hover:text-green-500" />
</div>
{tweet.retweets.length > 0 && (
<span className="group-hover:text-green-500 text-sm">
{tweet.retweets.length}
</span>
)}
</div>
<div className="flex items-center space-x-1 group">
<div className="icon group-hover:bg-pink-600/10" onClick={handleLike}>
{liked ? (
<HeartIconFilled className="h-5 text-pink-600" />
) : (
<HeartIcon className="h-5 group-hover:text-pink-600" />
)}
</div>
{likes > 0 && (
<span className={`group-hover:text-pink-600 text-sm ${
liked && "text-pink-600"
}`}>
{likes}
</span>
)}
</div>
<div className="icon group">
<ShareIcon className="h-5 group-hover:text-[#1d9bf0]" />
</div>
</div>
</div>
</div>
);
};
export default Tweet;
- Create the Input component (src/components/Feed/Input.tsx):
import React, { useState, useRef } from 'react';
import {
CalendarIcon,
ChartBarIcon,
EmojiHappyIcon,
PhotographIcon,
XIcon,
} from '@heroicons/react/outline';
import { db, storage } from '../../firebase';
import { addDoc, collection, serverTimestamp } from 'firebase/firestore';
import { getDownloadURL, ref, uploadString } from 'firebase/storage';
const Input = () => {
const [input, setInput] = useState("");
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const filePickerRef = useRef<HTMLInputElement>(null);
const addImageToPost = (e: React.ChangeEvent<HTMLInputElement>) => {
const reader = new FileReader();
if (e.target.files?.[0]) {
reader.readAsDataURL(e.target.files[0]);
}
reader.onload = (readerEvent) => {
setSelectedFile(readerEvent.target?.result as string);
};
};
const sendPost = async () => {
if (loading) return;
setLoading(true);
try {
const docRef = await addDoc(collection(db, "tweets"), {
text: input,
userId: "user-id", // Replace with actual user ID
timestamp: serverTimestamp(),
likes: [],
retweets: [],
replies: [],
quoteTweets: [],
});
if (selectedFile) {
const imageRef = ref(storage, `tweets/${docRef.id}/image`);
await uploadString(imageRef, selectedFile, "data_url");
const downloadURL = await getDownloadURL(imageRef);
await updateDoc(doc(db, "tweets", docRef.id), {
image: downloadURL,
});
}
setInput("");
setSelectedFile(null);
} catch (error) {
console.error("Error sending tweet:", error);
}
setLoading(false);
};
return (
<div className={`border-b border-gray-700 p-3 flex space-x-3 ${loading && "opacity-60"}`}>
<img
src="/default-avatar.png"
alt="Profile"
className="h-11 w-11 rounded-full cursor-pointer"
/>
<div className="w-full divide-y divide-gray-700">
<div className={`${selectedFile && "pb-7"} ${input && "space-y-2.5"}`}>
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="What's happening?"
rows={2}
className="bg-transparent outline-none text-[#d9d9d9] text-lg placeholder-gray-500 tracking-wide w-full min-h-[50px]"
/>
{selectedFile && (
<div className="relative">
<div
className="absolute w-8 h-8 bg-[#15181c] hover:bg-[#272c26] bg-opacity-75 rounded-full flex items-center justify-center top-1 left-1 cursor-pointer"
onClick={() => setSelectedFile(null)}
>
<XIcon className="text-white h-5" />
</div>
<img
src={selectedFile}
alt=""
className="rounded-2xl max-h-80 object-contain"
/>
</div>
)}
</div>