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

Add support for setting refs on elements for DOM reference #665

Closed
jstarry opened this issue Sep 27, 2019 · 0 comments · Fixed by #715
Closed

Add support for setting refs on elements for DOM reference #665

jstarry opened this issue Sep 27, 2019 · 0 comments · Fixed by #715
Labels

Comments

@jstarry
Copy link
Member

jstarry commented Sep 27, 2019

Proposal

Take inspiration from React Refs to get references to elements in the DOM

src/html/mod.rs

/// Wrapped Element reference for later use in Component lifecycle methods.
#[derive(PartialEq)]
pub struct ElementRef(RefCell<Option<Element>>);

impl Default for ElementRef {
    fn default() -> Self {
        ElementRef(RefCell::default())
    }
}

impl ElementRef {
    /// Get the wrapped Element reference if it exists
    pub fn get(&self) -> Option<Element> {
        self.0.borrow().clone()
    }

    /// Place an Element in a reference for later use
    pub fn set(&self, element: Element) {
        *self.0.borrow_mut() = Some(element);
    }
}

my_component.rs

#[derive(PartialEq, Properties)]
pub struct Props<T> {
    pub disabled: bool,
    pub select_ref: ElementRef,
}

// ...

fn mounted(&self) {
  if let Some(select) = self.props.select_ref.get() {
    // ...
  }
}

fn view(&self) -> Html<Self> {
  html! {
    <select ref={self.props.select_ref} disabled=self.props.disabled>
      // ...
    </select>
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant