Skip to main content

RenderOnce

Trait RenderOnce 

Source
pub trait RenderOnce: 'static {
    // Required method
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
}
Expand description

A component: a value that describes a pattern of elements and renders it once.

Use RenderOnce for reusable pieces of interface that keep no state of their own. Build the component from plain data, and derive IntoElement on it so it can be a child of an element. The component’s render takes self by value, and the component is consumed when it is drawn. A component can’t call Context::notify, because it has no entity. To report events, store a callback in the component and let the parent view decide what the callback does. Use Render for a piece of interface that holds state.

Elements that need state across frames need ids. Pass the id in from the parent, and use it with InteractiveElement::id. GPUI scopes a component’s elements under the component’s type name, so two instances of the same component side by side would otherwise share their state.

§Example

use std::{cell::Cell, rc::Rc};

use gpui::{App, Context, IntoElement, Render, RenderOnce, TestApp, Window, div, prelude::*};

#[derive(IntoElement)]
struct Badge {
    renders: Rc<Cell<usize>>,
}

impl RenderOnce for Badge {
    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
        self.renders.set(self.renders.get() + 1);
        div().child("3")
    }
}

struct Inbox {
    renders: Rc<Cell<usize>>,
}

impl Render for Inbox {
    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
        div().child(Badge {
            renders: self.renders.clone(),
        })
    }
}

let renders = Rc::new(Cell::new(0));
let mut app = TestApp::new();
let mut window = app.open_window({
    let renders = renders.clone();
    move |_window, _cx| Inbox { renders }
});

renders.set(0);
// Notify the view so the next draw renders it again instead of reusing its output.
window.update(|_, _, cx| cx.notify());
window.draw();
assert_eq!(renders.get(), 1);

Required Methods§

Source

fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement

Builds the component’s element tree. Takes self by value, so the component is used up.

GPUI calls this once for each time the component appears in a frame. Return the elements the component shows.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§