Syntax Highlighting Showcase

This page demonstrates the beautiful syntax highlighting capabilities of our enhanced CodeBlock component.

JavaScript Example

๐ŸŸจJavaScript
// JavaScript with colorful syntax highlighting
import React, { useState, useEffect } from 'react';

const MyComponent = ({ title, isVisible = true }) => {
  const [count, setCount] = useState(0);
  const [data, setData] = useState(null);
  
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('/api/data');
        const result = await response.json();
        setData(result);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    
    fetchData();
  }, []);

  const handleClick = () => {
    setCount(prev => prev + 1);
  };

  return (
    

{title}

{isVisible && (

Count: {count}

{data &&
{JSON.stringify(data, null, 2)}
}
)}
); }; export default MyComponent;

TypeScript Example

๐Ÿ”ทTypeScript
// TypeScript with enhanced syntax highlighting
interface User {
  id: number;
  name: string;
  email?: string;
  roles: string[];
}

type UserAction = 'create' | 'update' | 'delete';

class UserService {
  private users: User[] = [];

  constructor(private apiUrl: string) {}

  async getUser(id: number): Promise {
    const response = await fetch(`${this.apiUrl}/users/${id}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  }

  createUser>(userData: T): User {
    const newUser: User = {
      id: Math.random(),
      ...userData,
    };
    this.users.push(newUser);
    return newUser;
  }
}

// Generic function with constraints
function processData(
  items: T[],
  processor: (item: T) => T
): T[] {
  return items.map(processor);
}

React JSX Example

โš›๏ธJSX
// JSX with beautiful tag highlighting
import React from 'react';
import { Button, Card, Text } from 'rn-base-components';

const UserProfile = ({ user, onEdit, onDelete }) => {
  return (
    
      
{`${user.name}'s
{user.name} {user.email}
); }; export default UserProfile;

JSON Example

๐Ÿ“„JSON
{
  "name": "rn-base-components",
  "version": "1.0.0",
  "description": "Modern React Native component library",
  "main": "index.js",
  "scripts": {
    "build": "tsc && rollup -c",
    "test": "jest --coverage",
    "lint": "eslint src/**/*.{ts,tsx}"
  },
  "dependencies": {
    "react": "^18.0.0",
    "react-native": "^0.72.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.0",
    "typescript": "^5.0.0",
    "jest": "^29.0.0"
  },
  "keywords": [
    "react-native",
    "components",
    "ui-kit",
    "typescript"
  ],
  "author": "Saigon Technology",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/saigontechnology/rn-base-components"
  },
  "bugs": {
    "url": "https://github.com/saigontechnology/rn-base-components/issues"
  },
  "homepage": "https://rn-base-components.vercel.app"
}

CSS Example

๐ŸŽจCSS
/* CSS with beautiful property highlighting */
.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto;
  font-size: 16px;
  font-weight: 600;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  background: linear-gradient(135deg, #3b82f6, #1e40af);
  color: white;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
}

.button:active {
  transform: translateY(0);
}

.button--secondary {
  background: transparent;
  color: #3b82f6;
  border: 2px solid #3b82f6;
}

@media (max-width: 768px) {
  .button {
    font-size: 14px;
    padding: 10px 20px;
  }
}

Bash/Shell Example

๐Ÿ’ปBash
#!/bin/bash
# Installation script with syntax highlighting

set -e

echo "๐Ÿš€ Installing RN Base Components..."

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "โŒ Node.js is not installed. Please install Node.js first."
    exit 1
fi

# Check Node version
NODE_VERSION=$(node --version | cut -d'.' -f1 | sed 's/v//')
if [ "$NODE_VERSION" -lt 16 ]; then
    echo "โŒ Node.js version 16 or higher is required."
    exit 1
fi

# Install dependencies
echo "๐Ÿ“ฆ Installing dependencies..."
if [ -f "package-lock.json" ]; then
    npm ci
elif [ -f "yarn.lock" ]; then
    yarn install --frozen-lockfile
else
    npm install
fi

# Run build
echo "๐Ÿ”จ Building project..."
npm run build

# Run tests
echo "๐Ÿงช Running tests..."
npm test -- --coverage --silent

echo "โœ… Installation completed successfully!"
echo "๐ŸŽ‰ You can now use RN Base Components in your project!"

Python Example

๐ŸPython
# Python with beautiful syntax highlighting
from typing import List, Dict, Optional, Union
import asyncio
import json

class ComponentGenerator:
    """Generate React Native components dynamically."""
    
    def __init__(self, template_path: str):
        self.template_path = template_path
        self.components: Dict[str, str] = {}
    
    @staticmethod
    def validate_props(props: Dict[str, any]) -> bool:
        """Validate component properties."""
        required_fields = ['name', 'type', 'props']
        return all(field in props for field in required_fields)
    
    async def generate_component(
        self, 
        name: str, 
        props: List[Dict[str, Union[str, bool, int]]]
    ) -> Optional[str]:
        """Generate a component with given properties."""
        
        if not self.validate_props({'name': name, 'type': 'component', 'props': props}):
            raise ValueError(f"Invalid props for component: {name}")
        
        # Process props
        prop_definitions = []
        for prop in props:
            prop_type = prop.get('type', 'string')
            is_required = prop.get('required', False)
            default_value = prop.get('default', None)
            
            definition = f"{prop['name']}: {prop_type}"
            if not is_required:
                definition += " | undefined"
            
            prop_definitions.append(definition)
        
        # Generate component code
        component_code = f"""
import React from 'react';
import {{ View, Text, StyleSheet }} from 'react-native';

interface {name}Props {{
  {'; '.join(prop_definitions)};
}}

const {name}: React.FC<{name}Props> = (props) => {{
  return (
    
      Hello from {name}!
    
  );
}};

const styles = StyleSheet.create({{
  container: {{
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  }},
}});

export default {name};
"""
        
        self.components[name] = component_code
        return component_code

# Usage example
async def main():
    generator = ComponentGenerator('./templates')
    
    component = await generator.generate_component(
        'CustomButton',
        [
            {'name': 'title', 'type': 'string', 'required': True},
            {'name': 'onPress', 'type': 'function', 'required': True},
            {'name': 'disabled', 'type': 'boolean', 'default': False}
        ]
    )
    
    print("Generated component:", component)

if __name__ == "__main__":
    asyncio.run(main())

Amazing! Now every code block displays with beautiful, colorful syntax highlighting that makes code much easier to read and understand! ๐ŸŒˆโœจ