напиши полноценный сайт для продажи кроссовок и интересным дизайном и полным…
- User
напиши полноценный сайт для продажи кроссовок и интересным дизайном и полным функционалом код должен быть с расширением .tsx
- Assistant
напиши полноценный сайт для продажи кроссовок и интересным дизайном и полным функционалом код должен быть с расширением .tsx
Создание полноценного сайта для продажи кроссовок с интересным дизайном и полным функционалом требует структурированного подхода. Ниже представлен пример простого e-commerce сайта на React с использованием TypeScript и Next.js для серверного рендеринга. Этот пример охватывает основные компоненты: главная страница, страница продукта, корзина и навигация.
Создайте новый проект Next.js с TypeScript:
npx create-next-app@latest my-sneaker-store --typescript
cd my-sneaker-store
Установите необходимые зависимости:
npm install styled-components @types/styled-components
npm install react-icons
Настройте styled-components для Next.js:
Создайте или измените файл _document.tsx для поддержки styled-components.
// pages/_document.tsx
import Document, { DocumentContext, DocumentInitialProps, Html, Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
render() {
return (
<Html>
<Head>
{/* Здесь можно добавить дополнительные теги Head */}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
Создайте структуру проекта:
my-sneaker-store/
├── components/
│ ├── Header.tsx
│ ├── Footer.tsx
│ ├── ProductCard.tsx
│ └── Navbar.tsx
├── pages/
│ ├── index.tsx
│ ├── product/
│ │ └── [id].tsx
│ ├── _app.tsx
│ └── cart.tsx
├── styles/
│ └── globals.css
├── types/
│ └── product.d.ts
└── public/
└── images/
└── ... (ваши изображения)
Определите типы данных:
Создайте файл types/product.d.ts для описания типа продукта.
// types/product.d.ts
export interface Product {
id: number
name: string
description: string
price: number
image: string
}
Создайте фиктивные данные продуктов:
Для демонстрации создадим файл data/products.ts.
// data/products.ts
import { Product } from '../types/product'
export const products: Product[] = [
{
id: 1,
name: 'Nike Air Max',
description: 'Комфортные и стильные кроссовки от Nike.',
price: 120,
image: '/images/nike-air-max.jpg',
},
{
id: 2,
name: 'Adidas Ultraboost',
description: 'Обеспечивают превосходную амортизацию.',
price: 150,
image: '/images/adidas-ultraboost.jpg',
},
// Добавьте больше продуктов по необходимости
]
Создайте компонент Header:
// components/Header.tsx
import Link from 'next/link'
import styled from 'styled-components'
const HeaderContainer = styled.header`
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
background-color: #000;
color: #fff;
`
const Logo = styled.h1`
font-size: 24px;
`
const Nav = styled.nav`
a {
margin-left: 20px;
color: #fff;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
`
const Header: React.FC = () => {
return (
<HeaderContainer>
<Logo>
<Link href="/">SneakerStore</Link>
</Logo>
<Nav>
<Link href="/">Главная</Link>
<Link href="/cart">Корзина</Link>
</Nav>
</HeaderContainer>
)
}
export default Header
Создайте компонент ProductCard:
// components/ProductCard.tsx
import Link from 'next/link'
import styled from 'styled-components'
import { Product } from '../types/product'
const Card = styled.div`
border: 1px solid #eaeaea;
border-radius: 10px;
padding: 20px;
text-align: center;
transition: box-shadow 0.3s;
&:hover {
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.1);
}
`
const ProductImage = styled.img`
max-width: 100%;
height: auto;
border-radius: 10px;
`
const ProductName = styled.h2`
font-size: 20px;
margin: 10px 0;
`
const ProductPrice = styled.p`
font-size: 18px;
color: #0070f3;
`
const ProductCard: React.FC<{ product: Product }> = ({ product }) => {
return (
<Card>
<Link href={`/product/${product.id}`}>
<a>
<ProductImage src={product.image} alt={product.name} />
<ProductName>{product.name}</ProductName>
<ProductPrice>${product.price}</ProductPrice>
</a>
</Link>
</Card>
)
}
export default ProductCard
Создайте страницу главной страницы:
// pages/index.tsx
import Head from 'next/head'
import styled from 'styled-components'
import Header from '../components/Header'
import ProductCard from '../components/ProductCard'
import { products } from '../data/products'
const Container = styled.div`
max-width: 1200px;
margin: 0 auto;
padding: 20px;
`
const Grid = styled.div`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
`
const Home: React.FC = () => {
return (
<>
<Head>
<title>SneakerStore - Главная</title>
</Head>
<Header />
<Container>
<h1>Наши Кроссовки</h1>
<Grid>
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</Grid>
</Container>
</>
)
}
export default Home
Создайте страницу деталей продукта:
// pages/product/[id].tsx
import { useRouter } from 'next/router'
import styled from 'styled-components'
import Header from '../../components/Header'
import { products } from '../../data/products'
import { Product } from '../../types/product'
const Container = styled.div`
max-width: 1200px;
margin: 0 auto;
padding: 20px;
display: flex;
gap: 20px;
`
const Image = styled.img`
max-width: 500px;
width: 100%;
border-radius: 10px;
`
const Details = styled.div`
flex: 1;
`
const ProductName = styled.h1`
font-size: 32px;
margin-bottom: 20px;
`
const ProductDescription = styled.p`
font-size: 18px;
margin-bottom: 20px;
`
const ProductPrice = styled.p`
font-size: 24px;
color: #0070f3;
margin-bottom: 20px;
`
const BuyButton = styled.button`
padding: 10px 20px;
background-color: #0070f3;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: #005bb5;
}
`
const ProductPage: React.FC = () => {
const router = useRouter()
const { id } = router.query
const product: Product | undefined = products.find((p) => p.id === Number(id))
if (!product) {
return <p>Продукт не найден</p>
}
const handleBuy = () => {
// Логика добавления в корзину
alert('Добавлено в корзину!')
}
return (
<>
<Header />
<Container>
<Image src={product.image} alt={product.name} />
<Details>
<ProductName>{product.name}</ProductName>
<ProductDescription>{product.description}</ProductDescription>
<ProductPrice>${product.price}</ProductPrice>
<BuyButton onClick={handleBuy}>Купить</BuyButton>
</Details>
</Container>
</>
)
}
export default ProductPage
Создайте страницу корзины:
// pages/cart.tsx
import { useState } from 'react'
import styled from 'styled-components'
import Header from '../components/Header'
const Container = styled.div`
max-width: 1200px;
margin: 0 auto;
padding: 20px;
`
const CartItem = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 0;
border-bottom: 1px solid #eaeaea;
`
const Total = styled.p`
text-align: right;
font-size: 24px;
margin-top: 20px;
`
const CheckoutButton = styled.button`
padding: 10px 20px;
background-color: #0070f3;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
float: right;
&:hover {
background-color: #005bb5;
}
`
const Cart: React.FC = () => {
// Для демонстрации используем состояние
const [cartItems, setCartItems] = useState<{ name: string; price: number }[]>([
{ name: 'Nike Air Max', price: 120 },
{ name: 'Adidas Ultraboost', price: 150 },
])
const total = cartItems.reduce((acc, item) => acc + item.price, 0)
const handleCheckout = () => {
alert('Переход к оформлению заказа!')
}
return (
<>
<Header />
<Container>
<h1>Ваша Корзина</h1>
{cartItems.length === 0 ? (
<p>Ваша корзина пуста.</p>
) : (
<>
{cartItems.map((item, index) => (
<CartItem key={index}>
<span>{item.name}</span>
<span>${item.price}</span>
</CartItem>
))}
<Total>Итого: ${total}</Total>
<CheckoutButton onClick={handleCheckout}>Оформить Заказ</CheckoutButton>
</>
)}
</Container>
</>
)
}
export default Cart
Обновите файл _app.tsx для глобальных стилей:
// pages/_app.tsx
import type { AppProps } from 'next/app'
import Head from 'next/head'
import '../styles/globals.css'
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<Component {...pageProps} />
</>
)
}
export default MyApp
Добавьте глобальные стили:
Создайте или обновите styles/globals.css:
/* styles/globals.css */
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
background-color: #f5f5f5;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
Добавьте изображения продуктов:
Поместите изображения ваших кроссовок в папку public/images/. Убедитесь, что названия файлов соответствуют тем, что указаны в данных продуктов (nike-air-max.jpg, adidas-ultraboost.jpg и т.д.).
Запустите проект:
npm run dev
Перейдите в браузер по адресу http://localhost:3000, чтобы увидеть ваш сайт.
Этот пример предоставляет базовую функциональность. Для полноценного магазина рекомендую добавить следующие функции:
Управление состоянием корзины:
Аутентификация пользователей:
База данных и API:
Оплата и оформление заказа:
Адаптивный дизайн и улучшение UX/UI:
SEO-оптимизация:
Этот пример должен помочь вам начать разработку собственного интернет-магазина кроссовок. Не забудьте учитывать безопасность, производительность и пользовательский опыт при дальнейшем развитии проекта.
Not yet included in a published release.