Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
2.68 kB

htr Rust library usage

htr transforms HTML into React JSX markup, which helps when converting scraped raw HTML back into the form it would have in a valid React codebase.

Add dependency

[dependencies]
htr = "0.5.26"

Transform props only

Convert HTML attributes/styles to their React equivalents, keeping the markup:

extern crate htr;
use htr::convert_props_react;

fn main(){
    let html = r#"<div class="something" for="mystuff" tabindex="2" style="color: white; background-color: black">"#;
    let react_html = convert_props_react(html.to_string());

    println!("{}", react_html);
    // <div className="something" htmlFor="mystuff" tabIndex="2" style={{color: "white", backgroundColor: "black"}}>
}

Convert HTML to a full React component

convert_to_react takes the HTML string and a component name and returns a complete React component:

extern crate htr;
use htr::convert_to_react;

/// convert html to react component
fn main(){
    let html = r#"
        <script>window.alert()</script>
        <div class="something" for="mystuff" tabindex="2" style="color: white; background-color: black">
            <div class="child" for="mychildstuff" tabindex="2">
                child
            </div>
        </div>
        <span class="react" style="position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 577px; "
        ></span>
        "#;

    let react_component = convert_to_react(&html.to_string(), "Something");

    println!("{}", react_component);
    // import React from "react"
    //
    // function Something() {
    //     return (
    //        <>
    //            <script>{`window.alert()`}</script>
    //                <div className="something" htmlFor="mystuff" tabIndex="2" style={{color: "white", backgroundColor: "black"}}>
    //                  <div className="child" htmlFor="mychildstuff" tabIndex="2">
    //                      child
    //                  </div>
    //              </div>
    //              <span className="react" style={{position: "relative", display: "block", marginLeft: "auto", marginRight: "auto", maxWidth: "577px"}}
    //              ></span>
    //        </>
    //     )
    // }
}

Input / output format

  • Input: raw HTML as a String (props conversion) or &String plus a component name (full component conversion).
  • Output: React JSX — converted attributes (class → className, for → htmlFor, tabindex → tabIndex), inline style strings as style objects, and, for component conversion, a complete component wrapped with import React from "react" and a fragment root.