Skip to content

Instantly share code, notes, and snippets.

@soaxelbrooke
Created August 23, 2020 04:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soaxelbrooke/0b808bc495a3e2618311600d08cdb381 to your computer and use it in GitHub Desktop.
Save soaxelbrooke/0b808bc495a3e2618311600d08cdb381 to your computer and use it in GitHub Desktop.
Example Handling Input Files With Yew
use yew::events::ChangeData;
use yew::web_sys::File;
use yew::prelude::*;
pub struct MyFileInput {
link: ComponentLink<Self>,
file: Option<File>,
}
pub enum Msg {
SelectFile(Option<File>),
ClearFile,
}
impl Component for MyFileInput {
type Properties = ();
type Message = Msg;
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
file: None,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::SelectFile(file) => {
self.file = file;
},
Msg::ClearFile => {
self.file = None;
},
}
true
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false // No properties, so it should never change based on props
}
fn view(&self) -> Html {
match &self.file {
Some(file) => html! {
<div>
<p>{ "Filename: "}<span>{ file.name() }</span></p>
<p>{ "Last Modified: " }<span>{ file.last_modified() }</span></p>
<p>{ "Size: " }<span>{ file.size() }</span></p>
<button onclick=self.link.callback(|_| Msg::ClearFile)>{ "Clear" }</button>
</div>
},
None => html! {
<input type="file" id="file-input" onchange=self.link.callback(|cd: ChangeData| {
match cd {
ChangeData::Files(file_list) => {
log::info!("File list: {:?}", file_list.get(0));
Msg::SelectFile(file_list.get(0))
},
default => Msg::ClearFile
}
})/>
},
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment