DEV Community

harshit-lyzr
harshit-lyzr

Posted on

Building an HTML to ReactJS Converter with Streamlit and Lyzr Automata

ReactJS has revolutionized front-end development with its component-based architecture and efficient state management. However, converting existing HTML, CSS, and JavaScript code into React components can be a daunting task. This blog post will guide you through building an HTML to ReactJS converter using Streamlit and Lyzr Automata. By leveraging the power of generative AI models, this application streamlines the conversion process, making it more efficient and user-friendly.

Problem:
Developers often face the challenge of migrating legacy web projects from HTML, CSS, and JavaScript to a modern ReactJS framework. This manual conversion process involves breaking down the HTML structure into reusable React components, managing state effectively, and ensuring the overall maintainability and performance of the codebase. The complexity of this task can lead to increased development time, potential for bugs, and a steep learning curve for developers not proficient in ReactJS.

Objective:
To address this challenge, we propose developing an AI-powered HTML to ReactJS converter application. This tool will leverage the capabilities of generative AI models to automate the conversion process, providing developers with a quick, efficient, and accurate way to transform their HTML, CSS, and JavaScript code into ReactJS components.

Scope:
The application will be built using Streamlit for the user interface and Lyzr Automata for integrating AI models. Users will input their HTML, CSS, and JavaScript code, and the application will output well-structured, maintainable ReactJS code. The tool will ensure the following:

Component Structure: The HTML design will be broken down into reusable React components with a clear hierarchy.
State Management: Identify components that require state management and implement appropriate solutions using React’s built-in hooks or external libraries.
Props and Data Flow: Clearly define data flow between components, specifying the necessary props and their types.

Setting Up the Environment
Imports:

Imports necessary libraries: streamlit, libraries from lyzr_automata

pip install lyzr_automata streamlit
Enter fullscreen mode Exit fullscreen mode
import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent,Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image
Enter fullscreen mode Exit fullscreen mode

Sidebar Configuration

api = st.sidebar.text_input("Enter our OPENAI API KEY Here", type="password")
if api:
    openai_model = OpenAIModel(
        api_key=api,
        parameters={
            "model": "gpt-4-turbo-preview",
            "temperature": 0.2,
            "max_tokens": 1500,
        },
    )
else:
    st.sidebar.error("Please Enter Your OPENAI API KEY")
Enter fullscreen mode Exit fullscreen mode

if api:: Checks if an API key is entered.

openai_model = OpenAIModel(): If a key is entered, creates an OpenAIModel object with the provided API key, model parameters (gpt-4-turbo-preview, temperature, max_tokens).
else: If no key is entered, displays an error message in the sidebar.

reactjs_conversion Function:

def reactjs_conversion(html, css, javascript):
    react_agent = Agent(
        prompt_persona=f"You are a Frontend Engineer with over 10 years of experience.",
        role="Frontend Engineer",
    )

    react_task = Task(
        name="Dataset generation",
        output_type=OutputType.TEXT,
        input_type=InputType.TEXT,
        model=openai_model,
        agent=react_agent,
        log_output=True,
        instructions=f"""
        We need to convert an existing HTML design with css and js into a ReactJS application. 
        The conversion should result in a well-structured, maintainable, and performant React codebase. 
        Follow Below Instructions:

        **Component Structure**:
        Break down the HTML design into reusable React components.
        Define a clear component hierarchy, ensuring components are logically organized and nested.

        **State Management**:
        Identify which components will need to manage state.
        Decide whether to use React's built-in state management (useState, useReducer) or an external library (Redux, MobX).

        **Props and Data Flow**:
        Determine how data will flow between components.
        Clearly define the props each component will require and their types.

        Only give ReactJS Code nothing apart from it.

        HTML: {html}
        CSS: {css}
        JAVASCRIPT: {javascript}


        """,
        )

    output = LinearSyncPipeline(
        name="Dataset Generation",
        completion_message="Dataset Generated!",
        tasks=[
            react_task
        ],
    ).run()
    return output[0]['task_output']
Enter fullscreen mode Exit fullscreen mode

Defines a function reactjs_conversion that takes HTML, CSS, and JavaScript code as input and returns the converted ReactJS code.
Creates a react_agent object defining the prompt persona as a Frontend Engineer for better task understanding.
Creates a react_task object specifying:
Task name: “Dataset generation”
Output type: Text (the generated ReactJS code)
Input type: Text (the provided HTML, CSS, and JS code)
Model: The openai_model object
Agent: The react_agent object
Instructions: A detailed prompt explaining the conversion task, emphasizing component structure, state management, props & data flow, and requesting only ReactJS code as output.
Creates a LinearSyncPipeline object to execute the task in a linear sequence.
Runs the pipeline and retrieves the task output, which is the generated ReactJS code.
Returns the retrieved output.

User Code Input:

col1, col2, col3 = st.columns(3)
with col1:
    html5 = st.text_area("Enter HTML code", height=300)

with col2:
    css3 = st.text_area("Enter CSS Code", height=300)

with col3:
    js = st.text_area("Enter JS code", height=300)
Enter fullscreen mode Exit fullscreen mode

Creates three columns using st.columns() for HTML, CSS, and JavaScript code input with text areas using st.text_area().

Generate Button and Output Display:

if st.button("Convert"):
    solution = reactjs_conversion(html5, css3, js)
    st.markdown(solution)
Enter fullscreen mode Exit fullscreen mode

Creates a button labeled “Convert” using st.button().
On clicking the button:
Calls the reactjs_conversion function with the entered HTML, CSS, and JS code.
Displays the converted ReactJS code using st.markdown().
Running the App
Finally, run the app using the following command in your terminal:

streamlit run app.py
Enter fullscreen mode Exit fullscreen mode

try it now: https://github.com/harshit-lyzr/reactjs_convertor

For more information explore the website: Lyzr

Contibute to Our Project: https://github.com/LyzrCore/lyzr-automata

Top comments (0)