or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

built-in-components.mdcaching.mdchildren.mdcomponents.mdcomposition.mdcontext.mddevelopment.mdelements.mdexperimental.mdhooks-context.mdhooks-effects.mdhooks-imperative.mdhooks-performance.mdhooks-state.mdhooks-transitions.mdindex.mdrefs.mdtransitions.md
tile.json

refs.mddocs/

Refs

Access DOM nodes and customize ref values.

createRef

Creates a ref object for class components. Returns object with .current property.

function createRef<T>(): RefObject<T>;

interface RefObject<T> {
  readonly current: T | null;
}
class TextInput extends Component {
  inputRef = createRef();
  
  focusInput = () => {
    this.inputRef.current?.focus();  // Use optional chaining
  };
  
  render() {
    return <input ref={this.inputRef} />;
  }
}

forwardRef

Forward ref to child component. Required to pass refs to function components.

function forwardRef<P, T>(
  render: (props: P, ref: Ref<T>) => ReactElement | null
): ComponentType<P & { ref?: Ref<T> }>;

type Ref<T> = RefObject<T> | ((instance: T | null) => void) | null;
const Input = forwardRef((props, ref) => {
  return <input ref={ref} {...props} />;
});

// Parent uses ref
const inputRef = useRef(null);
<Input ref={inputRef} />
inputRef.current?.focus();

// With useImperativeHandle for custom API
const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef();
  
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    clear: () => inputRef.current.value = ''
  }));
  
  return <input ref={inputRef} {...props} />;
});