Skip to content

Commit

Permalink
Close #28: leverage html-react-parser to properly handle HTML() insid…
Browse files Browse the repository at this point in the history
…e of JSXTag
  • Loading branch information
cpsievert committed Apr 7, 2022
1 parent a78b32a commit 58024f0
Show file tree
Hide file tree
Showing 5 changed files with 316 additions and 271 deletions.
22 changes: 22 additions & 0 deletions htmltools/_jsx.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
HTMLDependency,
)
from ._versions import versions
from . import tags

__all__ = (
"jsx",
Expand Down Expand Up @@ -123,6 +124,8 @@ def tagify(self) -> Tag:
# metadata nodes. This could be done in two separate passes, but it's more
# efficient to do it in one pass.
def tagify_tagifiable_and_get_metadata(x: Any) -> Any:
if isinstance(x, HTML):
x = html_string_component(html_as_string(x))
if isinstance(x, Tagifiable) and not isinstance(x, (Tag, JSXTag)):
x = x.tagify()
else:
Expand Down Expand Up @@ -371,6 +374,25 @@ def __add__(self, other: Union[str, "jsx"]) -> str:
return jsx(res) if isinstance(other, jsx) else res


# JSX component that simply renders a raw HTML() string as DOM.
def html_string_component(x: str) -> JSXTag:
component = jsx_tag_create("ReactHtmlStringComponent")
component_dependency = _lib_dependency(
"html-react-parser",
script={"src": "html-react-parser.min.js"},
head=tags.script(
"window.ReactHtmlStringComponent = function(props) { return HTMLReactParser(props.children); };"
),
)
return component(x, component_dependency)


# TODO: this isn't an ideal way to remove HTML class of a string
# https://github.com/rstudio/py-htmltools/issues/15
def html_as_string(x: Union[HTML, str]) -> str:
return x + ""


def _lib_dependency(
pkg: str, script: Dict[str, str], **kwargs: object
) -> HTMLDependency:
Expand Down
2 changes: 1 addition & 1 deletion htmltools/_versions.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
versions = {"react": "17.0.2", "react-dom": "17.0.2"}
versions = {"react":"18.0.0","react-dom":"18.0.0","html-react-parser":"1.4.10"}
Loading

0 comments on commit 58024f0

Please sign in to comment.