Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leverage html-react-parser to properly handle HTML() inside of JSXTag #29

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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