hello_world_ssr.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // ANCHOR: all
  2. // ANCHOR: main
  3. #![allow(non_snake_case)]
  4. use axum::{response::Html, routing::get, Router};
  5. // import the prelude to get access to the `rsx!` macro and the `Scope` and `Element` types
  6. use dioxus::prelude::*;
  7. #[tokio::main]
  8. async fn main() {
  9. let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
  10. println!("listening on http://{}", addr);
  11. axum::Server::bind(&addr)
  12. .serve(
  13. Router::new()
  14. .route("/", get(app_endpoint))
  15. .into_make_service(),
  16. )
  17. .await
  18. .unwrap();
  19. }
  20. // ANCHOR_END: main
  21. // ANCHOR: endpoint
  22. async fn app_endpoint() -> Html<String> {
  23. // render the rsx! macro to HTML
  24. Html(dioxus_ssr::render_lazy(rsx! {
  25. div { "hello world!" }
  26. }))
  27. }
  28. // ANCHOR_END: endpoint
  29. // ANCHOR: second_endpoint
  30. async fn second_app_endpoint() -> Html<String> {
  31. // create a component that renders a div with the text "hello world"
  32. fn app(cx: Scope) -> Element {
  33. cx.render(rsx!(div { "hello world" }))
  34. }
  35. // create a VirtualDom with the app component
  36. let mut app = VirtualDom::new(app);
  37. // rebuild the VirtualDom before rendering
  38. let _ = app.rebuild();
  39. // render the VirtualDom to HTML
  40. Html(dioxus_ssr::render(&app))
  41. }
  42. // ANCHOR_END: second_endpoint
  43. // ANCHOR: component
  44. // define a component that renders a div with the text "Hello, world!"
  45. fn App(cx: Scope) -> Element {
  46. cx.render(rsx! {
  47. div {
  48. "Hello, world!"
  49. }
  50. })
  51. }
  52. // ANCHOR_END: component
  53. // ANCHOR_END: all