How to render optional props simply? #2240
-
Hi, I'm new to yew and trying to build a Tic-Tac-Toe example with functional components just like which in the tutorial of React.js. And I wonder what is a good and simple way to render optional props. To be more specific, in React.js we can write code like this: interface SquareProps {
value: "X" | "O" | undefined;
// some other props
}
const Square: React.FC<SquareProps> = (props) => {
const { value } = props;
return <button>{value}</button>
} And it won't display anything if I tried to translate these codes to yew: #[derive(PartialEq)]
enum SquareValue {
X,
O,
}
impl Display for SquareValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::X => write!(f, "X"),
Self::O => write!(f, "O"),
}
}
}
#[derive(Properties, PartialEq)]
struct SquareProps {
value: Option<SquareValue>,
}
#[function_component(Square)]
fn square(props: &SquareProps) -> Html {
match &props.value {
Some(v) => html! {
<button>{v}</button>
},
None => html! {
<button></button>
},
}
} This seems very annoying, and I need to write the same code for every optional value. Then I figure out another way by defining an #[derive(PartialEq)]
struct DisplayableOption<T: Display>(Option<T>);
impl<T: Display> Display for DisplayableOption<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
Some(t) => t.fmt(f),
None => write!(f, ""),
}
}
}
#[derive(Properties, PartialEq)]
struct SquareProps {
value: DisplayableOption<SquareValue>,
}
#[function_component(Square)]
fn square(props: &SquareProps) -> Html {
html! {
<button>{&props.value}</button>
}
} But this makes using Option's method cumbersome. So I come here to ask if a better practice existed. Please share your ideas with me. 😄 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Take a look at |
Beta Was this translation helpful? Give feedback.
-
@duskmoon314 in your case i would just do #[derive(PartialEq)]
enum SquareValue {
X,
O,
}
#[derive(Properties, PartialEq)]
struct SquareProps {
value: Option<SquareValue>,
} html! {
<button class="square" onclick={on_click}>{ value.unwrap_or("") }</button>
} |
Beta Was this translation helpful? Give feedback.
@duskmoon314 in your case i would just do