We recently released Vaadin 24.4.0.beta1. One of the new features that we’re introducing is a wrapper that helps you use React components from Flow. Here’s how you can try that out right now. Start by downloading https://start.vaadin.com/dl?preset=react&preset=partial-prerelease, extracting it, importing it to an IDE, and running the main method in Application.java
.
You can wrap any React component as a Flow component by wrapping it as a web component using a provided helper class. This helper will give access to state variables set from the server and provides a way of passing events back to the server.
src/main/frontend/reactExample.tsx
:
import { ReactElement, JSXElementConstructor } from "react";
import { ReactAdapterElement, RenderHooks } from "./generated/flow/ReactAdapter";
import { Button } from "@vaadin/react-components";
class ReactExample extends ReactAdapterElement {
protected render(hooks: RenderHooks): ReactElement {
const [value, setValue] = hooks.useState("value", "initial");
const sendEvent = hooks.useCustomEvent<string>("example-event");
return <Button onClick={() => sendEvent("Bar")}>{value}</Button>
}
}
customElements.define("react-example", ReactExample);
src/main/java/com/example/application/FlowView.java
:
package com.example.application;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.react.ReactAdapterComponent;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.Route;
@Route
@Menu
@JsModule("./reactExample.tsx")
@Tag("react-example")
public class FlowView extends ReactAdapterComponent {
public FlowView() {
getElement().addEventListener("example-event", event -> {
String value = event.getEventData().getString("event.detail");
setState("value", "Update: " + value);
}).addEventData("event.detail");
}
}