How to Run These Ratatui Examples
Every program on this page was compiled against Ratatui 0.30.2 with Rust 1.97 and produced no warnings. Create a project, add the crate, then save any example into the examples folder:
cargo new ratatui-examples && cd ratatui-examples
cargo add ratatui
mkdir examples
# save a file such as examples/counter.rs, then:
cargo run --example counterRun examples in a real terminal window. If a program is interrupted and the terminal looks wrong, type reset and press Enter.
Layout starter
Before the interactive examples, here is the smallest useful layout: a header, a sidebar, a main area and a footer.
use ratatui::crossterm::event::{self, Event};
use ratatui::layout::{Constraint, Layout};
use ratatui::widgets::{Block, Paragraph};
use ratatui::Frame;
fn main() -> std::io::Result<()> {
ratatui::run(|terminal| {
terminal.draw(render)?;
event::read().map(|_: Event| ())
})
}
fn render(frame: &mut Frame) {
let [header, body, footer] = Layout::vertical([
Constraint::Length(3),
Constraint::Min(0),
Constraint::Length(1),
])
.areas(frame.area());
let [sidebar, main] =
Layout::horizontal([Constraint::Percentage(30), Constraint::Fill(1)]).areas(body);
frame.render_widget(Block::bordered().title(" Header "), header);
frame.render_widget(Block::bordered().title(" Sidebar "), sidebar);
frame.render_widget(Block::bordered().title(" Main "), main);
frame.render_widget(Paragraph::new("Press any key to exit"), footer);
}Counter app: state and keyboard input
A struct holds the state, handle_key updates it and render draws it. This shape scales to large apps: add fields, add key bindings and split render into helpers.
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind};
use ratatui::layout::Alignment;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::{Block, Paragraph};
use ratatui::{DefaultTerminal, Frame};
#[derive(Default)]
struct App {
counter: i64,
exit: bool,
}
impl App {
fn run(&mut self, terminal: &mut DefaultTerminal) -> std::io::Result<()> {
while !self.exit {
terminal.draw(|frame| self.render(frame))?;
if let Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press {
self.handle_key(key);
}
}
}
Ok(())
}
fn handle_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Left | KeyCode::Char('j') => self.counter -= 1,
KeyCode::Right | KeyCode::Char('k') => self.counter += 1,
KeyCode::Char('q') | KeyCode::Esc => self.exit = true,
_ => {}
}
}
fn render(&self, frame: &mut Frame) {
let instructions = Line::from(vec![
" Decrement ".into(), "<Left>".blue().bold(),
" Increment ".into(), "<Right>".blue().bold(),
" Quit ".into(), "<Q> ".blue().bold(),
]);
let block = Block::bordered()
.title(Line::from(" Counter App ".bold()).centered())
.title_bottom(instructions.centered());
let text = Line::from(vec!["Value: ".into(), self.counter.to_string().yellow()]);
let paragraph = Paragraph::new(text)
.alignment(Alignment::Center)
.block(block);
frame.render_widget(paragraph, frame.area());
}
}
fn main() -> std::io::Result<()> {
ratatui::run(|terminal| App::default().run(terminal))
}Controls: Left/Right or j/k change the value; q or Esc quits.
Selectable list
ListState remembers the selected item between frames. select_next() and select_previous() move the highlight and clamp at the ends.
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{Block, List, ListState};
use ratatui::DefaultTerminal;
fn main() -> std::io::Result<()> {
ratatui::run(run)
}
fn run(terminal: &mut DefaultTerminal) -> std::io::Result<()> {
let items = ["Inbox", "Drafts", "Sent", "Archive", "Trash"];
let mut state = ListState::default().with_selected(Some(0));
loop {
terminal.draw(|frame| {
let list = List::new(items)
.block(Block::bordered().title(" Folders "))
.highlight_style(Style::new().bg(Color::Cyan).fg(Color::Black).add_modifier(Modifier::BOLD))
.highlight_symbol("> ");
frame.render_stateful_widget(list, frame.area(), &mut state);
})?;
if let Event::Key(key) = event::read()? {
if key.kind != KeyEventKind::Press {
continue;
}
match key.code {
KeyCode::Down | KeyCode::Char('j') => state.select_next(),
KeyCode::Up | KeyCode::Char('k') => state.select_previous(),
KeyCode::Char('q') => return Ok(()),
_ => {}
}
}
}
}Controls: Up/Down or j/k move; q quits.
Service status table
A Table with a header row, flexible column widths and a reversed highlight style. TableState tracks the selected row.
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::layout::Constraint;
use ratatui::style::{Style, Stylize};
use ratatui::widgets::{Block, Row, Table, TableState};
use ratatui::DefaultTerminal;
fn main() -> std::io::Result<()> {
ratatui::run(run)
}
fn run(terminal: &mut DefaultTerminal) -> std::io::Result<()> {
let rows = [
Row::new(["api-gateway", "running", "42 ms"]),
Row::new(["auth-service", "running", "18 ms"]),
Row::new(["billing-worker", "degraded", "310 ms"]),
Row::new(["search-index", "stopped", "-"]),
];
let widths = [Constraint::Fill(2), Constraint::Fill(1), Constraint::Length(8)];
let mut state = TableState::default().with_selected(0);
loop {
terminal.draw(|frame| {
let table = Table::new(rows.clone(), widths)
.header(Row::new(["Service", "Status", "Latency"]).bold().underlined())
.block(Block::bordered().title(" Services "))
.row_highlight_style(Style::new().reversed())
.highlight_symbol(">> ");
frame.render_stateful_widget(table, frame.area(), &mut state);
})?;
if let Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Down => state.select_next(),
KeyCode::Up => state.select_previous(),
KeyCode::Char('q') => return Ok(()),
_ => {}
}
}
}
}
}Controls: Up/Down move; q quits.
Line chart
The Chart widget plots (f64, f64) points with Braille markers for high resolution. Axis bounds and labels are set explicitly.
use ratatui::crossterm::event::{self, Event};
use ratatui::style::{Color, Style};
use ratatui::symbols::Marker;
use ratatui::widgets::{Axis, Block, Chart, Dataset, GraphType};
use ratatui::Frame;
fn main() -> std::io::Result<()> {
ratatui::run(|terminal| {
terminal.draw(render)?;
event::read().map(|_: Event| ())
})
}
fn render(frame: &mut Frame) {
let points: Vec<(f64, f64)> = (0..=100)
.map(|i| {
let x = i as f64 / 10.0;
(x, x.sin() * 4.0 + 5.0)
})
.collect();
let dataset = Dataset::default()
.name("sin(x)")
.marker(Marker::Braille)
.graph_type(GraphType::Line)
.style(Style::new().fg(Color::Cyan))
.data(&points);
let chart = Chart::new(vec![dataset])
.block(Block::bordered().title(" Signal "))
.x_axis(Axis::default().title("t").bounds([0.0, 10.0]).labels(["0", "5", "10"]))
.y_axis(Axis::default().title("value").bounds([0.0, 10.0]).labels(["0", "5", "10"]));
frame.render_widget(chart, frame.area());
}Controls: Any key quits.
Live dashboard with ticks
Polling with a timeout lets the loop update state four times per second even without input. Gauges, a sparkline and a bar chart share one vertical layout.
use std::time::{Duration, Instant};
use ratatui::crossterm::event::{self, Event, KeyCode};
use ratatui::layout::{Constraint, Layout};
use ratatui::style::{Color, Style};
use ratatui::widgets::{Bar, BarChart, BarGroup, Block, Gauge, Sparkline};
use ratatui::{DefaultTerminal, Frame};
struct App {
cpu: Vec<u64>,
memory: u16,
tick: u64,
}
impl App {
fn on_tick(&mut self) {
self.tick += 1;
let next = (self.tick * 37 % 100) / 2 + 20;
self.cpu.remove(0);
self.cpu.push(next);
self.memory = (40 + (self.tick * 7 % 50)) as u16;
}
}
fn main() -> std::io::Result<()> {
ratatui::run(run)
}
fn run(terminal: &mut DefaultTerminal) -> std::io::Result<()> {
let mut app = App { cpu: vec![0; 60], memory: 40, tick: 0 };
let tick_rate = Duration::from_millis(250);
let mut last_tick = Instant::now();
loop {
terminal.draw(|frame| render(frame, &app))?;
let timeout = tick_rate.saturating_sub(last_tick.elapsed());
if event::poll(timeout)? {
if let Event::Key(key) = event::read()? {
if key.code == KeyCode::Char('q') {
return Ok(());
}
}
}
if last_tick.elapsed() >= tick_rate {
app.on_tick();
last_tick = Instant::now();
}
}
}
fn render(frame: &mut Frame, app: &App) {
let [top, middle, bottom] = Layout::vertical([
Constraint::Length(3),
Constraint::Percentage(50),
Constraint::Fill(1),
])
.areas(frame.area());
let gauge = Gauge::default()
.block(Block::bordered().title(" Memory "))
.gauge_style(Style::new().fg(Color::Green))
.percent(app.memory);
frame.render_widget(gauge, top);
let sparkline = Sparkline::default()
.block(Block::bordered().title(" CPU % "))
.data(&app.cpu)
.style(Style::new().fg(Color::Cyan));
frame.render_widget(sparkline, middle);
let bars = [("api", 42), ("db", 77), ("cache", 18), ("queue", 55)]
.map(|(label, value)| Bar::default().label(label).value(value));
let chart = BarChart::default()
.block(Block::bordered().title(" Requests/s "))
.data(BarGroup::default().bars(&bars))
.bar_width(7)
.bar_gap(2);
frame.render_widget(chart, bottom);
}Controls: Data updates every 250 ms; q quits.

Custom widget
Implementing Widget for a reference lets you render the same value repeatedly without cloning. The widget writes symbols and styles straight into the buffer.
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{self, Event};
use ratatui::layout::Rect;
use ratatui::style::{Color, Style};
use ratatui::widgets::Widget;
/// A horizontal progress strip that labels itself.
struct ProgressStrip<'a> {
label: &'a str,
ratio: f64,
color: Color,
}
impl Widget for &ProgressStrip<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
if area.height == 0 || area.width == 0 {
return;
}
let filled = (area.width as f64 * self.ratio.clamp(0.0, 1.0)).round() as u16;
for x in area.left()..area.right() {
let symbol = if x < area.left() + filled { "█" } else { "░" };
buf[(x, area.top())].set_symbol(symbol).set_style(Style::new().fg(self.color));
}
let text = format!(" {} {:>3.0}% ", self.label, self.ratio * 100.0);
buf.set_string(area.left() + 1, area.top(), text, Style::new().fg(Color::White).bg(Color::Black));
}
}
fn main() -> std::io::Result<()> {
let strip = ProgressStrip { label: "build", ratio: 0.64, color: Color::Cyan };
ratatui::run(|terminal| {
terminal.draw(|frame| {
let area = Rect { height: 1, ..frame.area() };
frame.render_widget(&strip, area);
})?;
event::read().map(|_: Event| ())
})
}Controls: Any key quits.
Mouse input
Mouse capture is enabled before the terminal starts and disabled afterwards. Each left click reports its column and row.
use ratatui::crossterm::event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, MouseEventKind};
use ratatui::crossterm::execute;
use ratatui::widgets::{Block, Paragraph};
use std::io::stdout;
fn main() -> std::io::Result<()> {
execute!(stdout(), EnableMouseCapture)?;
let mut last = String::from("Click anywhere (q quits)");
let result = ratatui::run(|terminal| loop {
terminal.draw(|frame| {
let p = Paragraph::new(last.as_str()).block(Block::bordered().title(" Mouse "));
frame.render_widget(p, frame.area());
})?;
match event::read()? {
Event::Mouse(m) if m.kind == MouseEventKind::Down(event::MouseButton::Left) => {
last = format!("Clicked at column {}, row {}", m.column, m.row);
}
Event::Key(k) if k.code == KeyCode::Char('q') => break Ok(()),
_ => {}
}
});
execute!(stdout(), DisableMouseCapture)?;
result
}Controls: Click anywhere; q quits.
Next Steps
Combine these building blocks: put the table inside the dashboard, add tabs to switch views, or turn the counter into a form. For deeper explanations read how to create a real-time dashboard, how to create custom widgets and the widgets reference. The official repository also contains a large set of demos you can run after cloning.