Tauri Frontend ↔ Backend Communication | Send Messages from React to Rust
Video: Tauri Frontend ↔ Backend Communication | Send Messages from React to Rust by Taught by Celeste AI - AI Coding Coach
Watch full page →Tauri Frontend ↔ Backend Communication | Send Messages from React to Rust
Connecting a React frontend with a Rust backend in a Tauri desktop app enables you to combine web UI with native performance. This example shows how to send a message from React to Rust using Tauri's invoke command and display the Rust response in the UI.
Code
// Rust backend (src-tauri/src/lib.rs)
use tauri::command;
#[command]
fn send_message(message: String) -> String {
format!("Rust received: '{}'. Hello from Rust!", message)
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![send_message])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
// React frontend (src/App.tsx)
import React, { useState } from 'react';
import { invoke } from '@tauri-apps/api/tauri';
function App() {
const [response, setResponse] = useState('');
async function handleSendMessage() {
// Call Rust backend command 'send_message' with a string argument
const res = await invoke('send_message', { message: 'Hello from React!' });
setResponse(res as string);
}
return (
<div className="min-h-screen bg-gradient-to-br from-gray-900 to-gray-700 flex flex-col items-center justify-center p-8 text-white">
<button
className="bg-green-500 hover:bg-green-600 px-6 py-3 rounded font-semibold"
onClick={handleSendMessage}
>
Send Message
</button>
<div className="mt-6 p-4 bg-gray-800 rounded w-full max-w-md text-center">
{response || 'Response will appear here'}
</div>
</div>
);
}
export default App;
Key Points
- Tauri commands in Rust are defined with the
#[command]attribute and registered viainvoke_handler. - The React frontend calls Rust commands asynchronously using Tauri's
invokefunction with the command name and parameters. - Data flows from React to Rust and back, enabling seamless communication between frontend UI and native backend logic.
- TypeScript ensures type safety when invoking Rust commands and handling responses.
- Styling with Tailwind CSS creates a clean UI to demonstrate the message roundtrip clearly.