How to import a component in Yew?

466 views Asked by At

So I have a main.rs file that looks like so:

fn main() {
    yew::Renderer::<App>::new().render();
}

But I need to import the App component into main.rs. From what I saw in a tutorial I should be able to do: use <name_of_app>::App;, but that does not work. It will tell me that <name_of_app> is not a part of the crate for me to use and Rust analyzer is not coming up with suggestions.

I tried this approach, but Rust analyzer is complaining that App is being defined multiple times:

mod App;
use App::App;

fn main() {
    yew::Renderer::<App>::new().render();
}
2

There are 2 answers

3
PitaJ On BEST ANSWER

You'll need to define a module for whatever file your App is defined in. mod name_of_app; use name_of_app::App;

src/main.rs

mod module_for_app;
use module_for_app::App;

fn main() {
    yew::Renderer::<App>::new().render();
}

src/module_for_app.rs

pub struct App {
   // ....
}

See the section from The Book on modules for more information

0
Maxwell On

I encountered the same problem, but I solved it in a different way, I hope you can refer to the following.

I have wrapped the render method of the App component inside the component file,like app.rs

#[function_component(App)]
fn app() -> Html {
  // some code
}

pub fn render() {
    yew::Renderer::<App>::new().render();
}

then in main.rs, you can use app mod and call app::render()

mod app;

fn main() {
    app::render();
}