Ratatui Widgets: Components, Styling and Practical Examples
Tour the built-in widget catalog, learn how styles, spans and blocks compose, and pick the right widget for each part of your interface.
Implement Widget and StatefulWidget, draw directly into the buffer, compose existing widgets and write snapshot tests for your components.

Ratatui's built-in widgets cover a lot of ground, but sooner or later you will want something they do not provide: a status pill, a heat map, a menu bar with your own highlighting rules or a domain-specific visualization. The good news is that custom widgets are first-class citizens. They implement the same traits as the built-in ones, render into the same buffer and slot into layouts without special handling. This guide shows how to implement Widget and StatefulWidget, write to the Buffer safely, compose existing widgets and test your work, with examples compiled and tested against Ratatui 0.30.2.
Not every piece of rendering code needs to become a widget. A helper function that takes &mut Frame, a Rect and some data is often enough, especially for one-off screens. A custom widget pays off when the same visual element appears in several places, when it needs its own configuration (colors, labels, alignment), when you want to test it in isolation, or when you plan to share it with other projects. Widgets also compose better: anything that accepts a widget, such as a layout helper or a popup function, accepts yours too.
A good rule of thumb is to start with a function, and promote it to a widget the second time you need it somewhere else or the first time you want to write a test for it. The promotion is mechanical: move the parameters into struct fields and the body into render.
A widget is any type that implements the Widget trait. The trait has a single method:
fn render(self, area: Rect, buf: &mut Buffer)
where
Self: Sized;It takes the widget by value, a rectangle to draw into and a mutable reference to the buffer. The buffer is a grid of Cell values, each holding a symbol and a style. Your job is to write the right cells inside area. When rendering finishes, Ratatui compares the buffer to the previous frame and sends only the changes to the terminal.
Widgets that need data to persist between frames implement StatefulWidget instead. It adds an associated State type and a third parameter, state: &mut Self::State. The built-in List and Table use this trait with ListState and TableState to remember selection and scroll offset.
Because render consumes the widget, implementing Widget directly for a type means you must rebuild or clone it every frame. That is fine for cheap, frame-scoped values. For widgets that hold more data, or for your whole App struct, implement the trait for a reference instead: impl Widget for &MyWidget. You can then call frame.render_widget(&my_widget, area) repeatedly without giving up ownership. Ratatui uses this pattern for its own widgets too.
The Buffer API is small and direct:
buf[(x, y)] indexes a cell by position and returns a mutable reference, on which you call set_symbol(), set_style(), set_fg() or set_bg().buf.set_string(x, y, text, style) writes a string starting at a position, handling wide characters correctly.buf.set_stringn(x, y, text, max_width, style) does the same but stops after a maximum width, which is how you avoid overflowing your area.buf.set_style(area, style) applies a style to a whole rectangle, useful for backgrounds and highlights.Coordinates are absolute, not relative to your area. Always start from area.left() and area.top(), and never write outside area. Indexing a position outside the buffer panics, so defensive widgets clip their area with area.intersection(buf.area) before drawing.
The following widget draws a single-line progress strip with a label on top of the bar. It fills cells proportionally to a ratio, writes the label with set_stringn so it never overflows, and includes a unit test. Save it as a standalone example and run cargo test --examples:
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Style};
use ratatui::widgets::Widget;
/// A one-line progress strip that labels itself.
pub struct ProgressStrip<'a> {
pub label: &'a str,
pub ratio: f64,
pub color: Color,
}
impl Widget for &ProgressStrip<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let area = area.intersection(buf.area); // never write outside the buffer
if area.is_empty() {
return;
}
let filled = (f64::from(area.width) * 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_stringn(
area.left() + 1,
area.top(),
text,
area.width.saturating_sub(1) as usize,
Style::new().fg(Color::White).bg(Color::Black),
);
}
}
fn main() {}
#[test]
fn renders_label_and_fill() {
let strip = ProgressStrip { label: "build", ratio: 0.5, color: Color::Cyan };
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 1));
(&strip).render(buf.area, &mut buf);
assert_eq!(buf[(0, 0)].symbol(), "█");
assert_eq!(buf[(19, 0)].symbol(), "░");
let line: String = (0..20).map(|x| buf[(x, 0)].symbol()).collect();
assert!(line.contains("build 50%"));
}A few design choices are worth copying. The ratio is clamped, so a caller passing 1.2 does not break rendering. The widget returns early for empty areas, which happen when layouts collapse in tiny terminals. And the styling is a field, so callers decide the color instead of the widget hard-coding it.
Many custom widgets are really combinations of existing ones. Inside your render method you can create a Block, compute its inner area with block.inner(area), render the block, and then render a Paragraph, a Line or another custom widget into the inner area. Because every widget implements Widget, you call .render(area, buf) on them directly, without a Frame.
Accepting an optional Block through a builder method, the way built-in widgets do, keeps your component consistent with the rest of the interface: users of the widget can choose borders, titles and padding.
When a widget needs to remember something between frames, separate the configuration (the widget) from the memory (the state). The menu bar below highlights the selected item. The widget is rebuilt each frame from a slice of labels, while MenuState lives in your application and survives across frames. It also demonstrates composition with an optional block and builder-style configuration:
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Style, Stylize};
use ratatui::text::Line;
use ratatui::widgets::{Block, StatefulWidget, Widget};
/// A horizontal menu whose selection lives in `MenuState`.
pub struct Menu<'a> {
items: &'a [&'a str],
block: Option<Block<'a>>,
}
#[derive(Default)]
pub struct MenuState {
pub selected: usize,
}
impl MenuState {
pub fn next(&mut self, len: usize) {
self.selected = (self.selected + 1) % len.max(1);
}
}
impl<'a> Menu<'a> {
pub fn new(items: &'a [&'a str]) -> Self {
Self { items, block: None }
}
pub fn block(mut self, block: Block<'a>) -> Self {
self.block = Some(block);
self
}
}
impl StatefulWidget for Menu<'_> {
type State = MenuState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
// Compose: let a Block draw the frame, then fill its inner area.
let inner = match self.block {
Some(block) => {
let inner = block.inner(area);
block.render(area, buf);
inner
}
None => area,
};
let spans: Vec<_> = self
.items
.iter()
.enumerate()
.map(|(i, item)| {
let text = format!(" {item} ");
if i == state.selected { text.black().on_cyan().bold() } else { text.into() }
})
.collect();
Line::from(spans).style(Style::new()).render(inner, buf);
}
}
fn main() {}
#[test]
fn highlights_selected_item() {
let items = ["File", "Edit", "View"];
let mut state = MenuState::default();
state.next(items.len());
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
Menu::new(&items).block(Block::bordered()).render(buf.area, &mut buf, &mut state);
assert_eq!(state.selected, 1);
assert_eq!(buf[(8, 1)].symbol(), "E");
}Render it with frame.render_stateful_widget(Menu::new(&items).block(block), area, &mut app.menu_state). Input handling stays in your app: call app.menu_state.next(items.len()) when the user presses Tab.
.style() and, where relevant, .highlight_style() builder methods instead of fixed colors.Styled for Stylize support. If your widget implements the Styled trait, callers can use shorthand like .red().bold() on it, just like built-in widgets.Style::patch and buf.set_style combine with existing styles, so a background set by a parent block is not lost.Terminal cells are not the same as characters. Most Latin letters take one cell, but many CJK characters and emoji take two, and some combining marks take none. If your widget writes symbols cell by cell with buf[(x, y)].set_symbol(), you are responsible for that arithmetic. Prefer set_string and set_stringn for text, because they measure display width with Unicode rules and leave the second cell of a wide character in the correct state. Reserve per-cell writes for single-width symbols such as box-drawing characters, blocks and Braille dots, which is exactly what bars, gauges and charts need.
Widgets are pure functions from inputs to buffer contents, which makes them easy to test. Render into Buffer::empty(area) and inspect cells, or build an expected buffer with Buffer::with_lines and compare whole buffers with assert_eq!, which prints a readable diff when the test fails. For full screens, a Terminal with TestBackend lets you test exactly what draw produces. Both test approaches appear in the examples above and pass on Ratatui 0.30.2.
Test edge cases explicitly: zero-width areas, one-row areas, very long labels, wide Unicode characters and ratios outside the expected range. These are the situations that cause panics in production.
Custom widgets run inside every frame, so keep render lean. Precompute expensive values, such as sorted data or formatted labels, in your application state, and let the widget only translate them into cells.
If your widget is useful beyond one project, publish it. Since Ratatui 0.30, widget libraries can depend on ratatui-core instead of the full ratatui crate. The core crate contains the Widget traits, Buffer, layout and style types, and it changes less often, so your crate needs fewer releases to stay compatible. Document which Ratatui versions you support and include a screenshot or a TestBackend-based example.

Implement it for a reference (&MyWidget) when the widget holds data you want to keep between frames, such as your app state. Implement it for the owned type when the widget is cheap and built fresh each frame.
It writes outside the buffer. Clip your area with area.intersection(buf.area) and only write between area.left()..area.right() and area.top()..area.bottom().
Yes. Call .render(area, buf) on built-in widgets inside your own render method, usually after computing sub-areas with a Layout or block.inner().
Render it into Buffer::empty(Rect::new(0, 0, w, h)) and assert on cells, or compare with a buffer created by Buffer::with_lines.
Since 0.30, depend on ratatui-core, which provides the traits and core types and changes less often than the full ratatui crate.
Custom widgets in Ratatui are ordinary Rust types that implement Widget or StatefulWidget and write cells into a Buffer. Implement them for references to avoid needless cloning, clip to your area, accept styles from callers, compose built-in widgets for borders and text, and keep persistent data in a separate state type. Add buffer-based tests and your components will stay reliable as your app grows. For every method on Buffer and Cell, see the Buffer documentation on docs.rs, and compare with the built-in widgets in our widgets reference or the widgets styling guide.