Skip to content

Instantly share code, notes, and snippets.

@ikhlaqmalik13
Created July 25, 2024 07:34
Show Gist options
  • Save ikhlaqmalik13/c15473bd91536afe626e800929beeca6 to your computer and use it in GitHub Desktop.
Save ikhlaqmalik13/c15473bd91536afe626e800929beeca6 to your computer and use it in GitHub Desktop.
JS to React Native python Script
import os
import re
def replace_html_elements(content):
replacements = {
'<div': '<View',
'</div>': '</View>',
'<p': '<Text',
'</p>': '</Text>',
'<span': '<Text',
'</span>': '</Text>',
'<a': '<TouchableOpacity',
'</a>': '</TouchableOpacity>',
'<img': '<Image',
'<ul': '<View',
'</ul>': '</View>',
'<li': '<View',
'</li>': '</View>',
'<button': '<TouchableOpacity',
'</button>': '</TouchableOpacity>',
'<input': '<TextInput',
}
for old, new in replacements.items():
content = content.replace(old, new)
return content
def adjust_imports(content):
content = re.sub(r'import (.*) from [\'"]next/(.+?)[\'"]', r'import \1 from "react-native"', content)
content = content.replace('import React from "react"', 'import React from "react"\nimport { View, Text, TouchableOpacity, Image, TextInput } from "react-native"')
# Add NativeWind import if not present
if 'import { styled } from "nativewind"' not in content:
content = 'import { styled } from "nativewind"\n' + content
return content
def modify_routing(content):
# Replace Next.js Link with React Navigation
content = content.replace('import Link from "next/link"', 'import { useNavigation } from "@react-navigation/native"')
content = re.sub(r'<Link href="([^"]+)">(.*?)</Link>', r'<TouchableOpacity onPress={() => navigation.navigate("\1")}>\2</TouchableOpacity>', content)
# Add navigation hook
if 'useNavigation' in content and 'const navigation = useNavigation()' not in content:
content = content.replace('function ', 'const navigation = useNavigation()\n\nfunction ', 1)
return content
def apply_nativewind_styling(content):
# Apply styled HOC to React Native components
components = ['View', 'Text', 'TouchableOpacity', 'Image', 'TextInput']
for component in components:
content = re.sub(f'<{component}', f'<styled.{component}', content)
content = re.sub(f'</{component}>', f'</styled.{component}>', content)
return content
def refactor_file(file_path):
with open(file_path, 'r') as file:
content = file.read()
content = replace_html_elements(content)
content = adjust_imports(content)
content = modify_routing(content)
content = apply_nativewind_styling(content)
with open(file_path, 'w') as file:
file.write(content)
def refactor_directory(directory):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.js') or file.endswith('.jsx'):
file_path = os.path.join(root, file)
refactor_file(file_path)
# Usage
src_directory = './new-react-native-project/src'
refactor_directory(src_directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment