or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

components.mdhocs.mdhooks.mdicu-macro.mdindex.mdssr.md

components.mddocs/

0

# React Components

1

2

React i18next provides specialized components for rendering translations with HTML interpolation, managing i18next context, and render prop patterns.

3

4

## Capabilities

5

6

### Trans Component

7

8

Component for rendering translations that contain HTML elements, React components, or complex interpolation. Parses translation strings with numbered placeholders and maps them to React elements.

9

10

```typescript { .api }

11

/**

12

* Component for complex translations with HTML/React element interpolation

13

* @param props - Trans component properties including i18nKey and interpolation options

14

*/

15

function Trans<

16

Key extends ParseKeys<Ns, TOpt, KPrefix>,

17

Ns extends Namespace = TypeOptions['defaultNS'],

18

KPrefix = undefined,

19

TContext extends string | undefined = undefined,

20

TOpt extends TOptions & { context?: TContext } = { context: TContext },

21

E = React.HTMLProps<HTMLDivElement>

22

>(props: TransProps<Key, Ns, KPrefix, TContext, TOpt, E>): React.ReactElement;

23

24

interface TransProps<Key, Ns, KPrefix, TContext, TOpt, E> extends E {

25

/** Template content with numbered placeholders */

26

children?: TransChild | readonly TransChild[];

27

/** React elements mapped to numbered placeholders */

28

components?: readonly React.ReactElement[] | { readonly [tagName: string]: React.ReactElement };

29

/** Count for pluralization */

30

count?: number;

31

/** Translation context for contextual variations */

32

context?: TContext;

33

/** Default translation if key is missing */

34

defaults?: string;

35

/** Custom i18next instance */

36

i18n?: i18n;

37

/** Translation key or array of keys */

38

i18nKey?: Key | Key[];

39

/** Namespace for the translation */

40

ns?: Ns;

41

/** Parent element type or component */

42

parent?: string | React.ComponentType<any> | null;

43

/** Additional translation options */

44

tOptions?: TOpt;

45

/** Values for interpolation */

46

values?: {};

47

/** Control HTML entity unescaping */

48

shouldUnescape?: boolean;

49

/** Override translation function */

50

t?: TFunction<Ns, KPrefix>;

51

}

52

53

type TransChild = React.ReactNode | Record<string, unknown>;

54

```

55

56

**Usage Examples:**

57

58

```typescript

59

import { Trans } from "react-i18next";

60

61

// Basic HTML interpolation

62

// Translation: "Go <1>there</1>."

63

function Navigation() {

64

return (

65

<Trans i18nKey="navigation.goThere">

66

Go <a href="/somewhere">there</a>.

67

</Trans>

68

);

69

}

70

71

// Component mapping with array

72

// Translation: "Hello <1><0>{{name}}</0></1>, you have <3>{{count}}</3> message."

73

function WelcomeMessage({ name, count }) {

74

return (

75

<Trans

76

i18nKey="welcome.message"

77

values={{ name, count }}

78

components={[

79

<strong />, // <0>

80

<span className="user" />, // <1>

81

null, // <2> (unused)

82

<b /> // <3>

83

]}

84

/>

85

);

86

}

87

88

// Component mapping with object

89

// Translation: "Visit our <Link>homepage</Link> or <Button>contact us</Button>."

90

function CallToAction() {

91

return (

92

<Trans

93

i18nKey="cta.message"

94

components={{

95

Link: <a href="/" />,

96

Button: <button onClick={handleContact} />

97

}}

98

/>

99

);

100

}

101

102

// With pluralization

103

// Translations: "You have {{count}} item" / "You have {{count}} items"

104

function ItemStatus({ count }) {

105

return (

106

<Trans i18nKey="itemCount" count={count} values={{ count }}>

107

You have <strong>{{count}}</strong> item

108

</Trans>

109

);

110

}

111

112

// With context

113

// Translations: "Go <1>there</1>." / "Go <1>home</1>." (context: "home")

114

function ContextualLink({ isHome }) {

115

return (

116

<Trans

117

i18nKey="navigation.go"

118

context={isHome ? "home" : undefined}

119

>

120

Go <a href={isHome ? "/" : "/somewhere"}>there</a>.

121

</Trans>

122

);

123

}

124

125

// Custom parent element

126

function FormattedTranslation() {

127

return (

128

<Trans

129

i18nKey="formatted.text"

130

parent="section"

131

className="translation-section"

132

>

133

This content will be wrapped in a section element.

134

</Trans>

135

);

136

}

137

```

138

139

### TransWithoutContext Component

140

141

Standalone Trans component that doesn't rely on React context, requiring explicit i18next instance.

142

143

```typescript { .api }

144

/**

145

* Trans component without context dependency - requires explicit i18next instance

146

* Available as separate import: react-i18next/TransWithoutContext

147

*/

148

const TransWithoutContext: typeof Trans;

149

```

150

151

**Usage Examples:**

152

153

```typescript

154

import { Trans } from "react-i18next/TransWithoutContext";

155

import i18next from "i18next";

156

157

// Explicit i18next instance required

158

function StandaloneTranslation() {

159

return (

160

<Trans

161

i18n={i18next}

162

i18nKey="standalone.message"

163

>

164

This works without <strong>context</strong>.

165

</Trans>

166

);

167

}

168

```

169

170

### I18nextProvider Component

171

172

React context provider that supplies i18next instance and configuration to child components.

173

174

```typescript { .api }

175

/**

176

* React context provider for i18next instance and configuration

177

* @param props - Provider props with i18next instance and optional default namespace

178

*/

179

function I18nextProvider(props: I18nextProviderProps): React.FunctionComponent;

180

181

interface I18nextProviderProps {

182

/** Child components that will have access to i18next context */

183

children?: React.ReactNode;

184

/** i18next instance to provide to children (required) */

185

i18n: i18n;

186

/** Default namespace(s) for child components */

187

defaultNS?: string | string[];

188

}

189

```

190

191

**Usage Examples:**

192

193

```typescript

194

import { I18nextProvider, useTranslation } from "react-i18next";

195

import i18next from "i18next";

196

197

// Basic provider setup

198

function App() {

199

return (

200

<I18nextProvider i18n={i18next}>

201

<HomePage />

202

<UserProfile />

203

</I18nextProvider>

204

);

205

}

206

207

// With default namespace

208

function DashboardApp() {

209

return (

210

<I18nextProvider i18n={i18next} defaultNS="dashboard">

211

<DashboardContent />

212

</I18nextProvider>

213

);

214

}

215

216

// Multiple providers for different sections

217

function MultiSectionApp() {

218

return (

219

<div>

220

<I18nextProvider i18n={adminI18n} defaultNS="admin">

221

<AdminPanel />

222

</I18nextProvider>

223

224

<I18nextProvider i18n={userI18n} defaultNS="user">

225

<UserSection />

226

</I18nextProvider>

227

</div>

228

);

229

}

230

231

function HomePage() {

232

const { t } = useTranslation(); // Uses i18n from provider

233

return <h1>{t('welcome')}</h1>;

234

}

235

```

236

237

### Translation Component (Render Prop)

238

239

Render prop component that provides translation function and related data to child render functions.

240

241

```typescript { .api }

242

/**

243

* Render prop component providing translation function and i18next data

244

* @param props - Component props with render function and configuration

245

*/

246

function Translation<

247

Ns extends FlatNamespace | $Tuple<FlatNamespace> | undefined = undefined,

248

KPrefix extends KeyPrefix<FallbackNs<Ns>> = undefined

249

>(props: TranslationProps<Ns, KPrefix>): React.ReactNode;

250

251

interface TranslationProps<Ns, KPrefix> {

252

/** Render function receiving translation data */

253

children: (

254

t: TFunction<FallbackNs<Ns>, KPrefix>,

255

options: {

256

i18n: i18n;

257

lng: string;

258

},

259

ready: boolean

260

) => React.ReactNode;

261

/** Namespace(s) for translations */

262

ns?: Ns;

263

/** Custom i18next instance */

264

i18n?: i18n;

265

/** Enable React Suspense */

266

useSuspense?: boolean;

267

/** Key prefix for translations */

268

keyPrefix?: KPrefix;

269

/** Namespace resolution mode */

270

nsMode?: 'fallback' | 'default';

271

}

272

```

273

274

**Usage Examples:**

275

276

```typescript

277

import { Translation } from "react-i18next";

278

279

// Basic render prop usage

280

function UserGreeting({ username }) {

281

return (

282

<Translation>

283

{(t, { i18n, lng }, ready) => {

284

if (!ready) return <div>Loading...</div>;

285

286

return (

287

<div>

288

<h1>{t('greeting', { name: username })}</h1>

289

<p>Current language: {lng}</p>

290

<button onClick={() => i18n.changeLanguage('es')}>

291

{t('switchToSpanish')}

292

</button>

293

</div>

294

);

295

}}

296

</Translation>

297

);

298

}

299

300

// With namespace and key prefix

301

function SettingsPanel() {

302

return (

303

<Translation ns="settings" keyPrefix="panel">

304

{(t, { i18n }) => (

305

<div className="settings-panel">

306

<h2>{t('title')}</h2> {/* settings:panel.title */}

307

<button onClick={() => i18n.reloadResources()}>

308

{t('refresh')} {/* settings:panel.refresh */}

309

</button>

310

</div>

311

)}

312

</Translation>

313

);

314

}

315

316

// Error handling and loading states

317

function StatusAwareComponent() {

318

return (

319

<Translation ns={['main', 'errors']}>

320

{(t, { i18n, lng }, ready) => {

321

if (!ready) {

322

return <div className="loading">{t('loading')}</div>;

323

}

324

325

return (

326

<div>

327

<h1>{t('main:welcome')}</h1>

328

{i18n.isInitialized ? (

329

<p>{t('main:ready', { language: lng })}</p>

330

) : (

331

<p>{t('errors:notInitialized')}</p>

332

)}

333

</div>

334

);

335

}}

336

</Translation>

337

);

338

}

339

```

340

341

## React Context

342

343

```typescript { .api }

344

/**

345

* React context providing i18next instance and configuration

346

*/

347

const I18nContext: React.Context<{

348

i18n: i18n;

349

defaultNS?: string | string[];

350

}>;

351

```

352

353

**Usage Examples:**

354

355

```typescript

356

import { useContext } from "react";

357

import { I18nContext } from "react-i18next";

358

359

// Direct context access

360

function DebugComponent() {

361

const { i18n, defaultNS } = useContext(I18nContext) || {};

362

363

return (

364

<div>

365

<p>Language: {i18n?.language}</p>

366

<p>Default NS: {defaultNS}</p>

367

<p>Initialized: {i18n?.isInitialized ? 'Yes' : 'No'}</p>

368

</div>

369

);

370

}

371

```

372

373

## Component Behavior

374

375

### Trans Component Parsing

376

377

The Trans component parses translation strings using numbered placeholders:

378

379

- `<0>` maps to first element in components array or components[0]

380

- `<1>` maps to second element in components array or components[1]

381

- Self-closing tags: `<0/>` renders as-is without children

382

- Nested elements: `<0><1>content</1></0>` creates nested structure

383

384

### HTML Support

385

386

Trans component supports basic HTML elements by default:

387

388

- Preserves: `<br>`, `<strong>`, `<i>`, `<p>` (configurable)

389

- Escapes: Other HTML elements for security

390

- Control via `transSupportBasicHtmlNodes` and `transKeepBasicHtmlNodesFor` options

391

392

### Error Handling

393

394

Components handle common error scenarios:

395

396

- Missing translations: Shows translation key or defaults

397

- Invalid component mapping: Renders placeholder or children as-is

398

- Context unavailable: Falls back to global i18next instance

399

- Type errors: Provides TypeScript warnings during development