0
# Component Control
1
2
Programmatic control methods for navigation and component manipulation. This covers all methods available for controlling the PDF component programmatically.
3
4
## Capabilities
5
6
### Page Navigation
7
8
Programmatically navigate to specific pages within the PDF document.
9
10
```typescript { .api }
11
/**
12
* Navigate to a specific page in the PDF
13
* @param pageNumber - Target page number (1-based)
14
* @throws Error if pageNumber is not a valid number
15
*/
16
setPage(pageNumber: number): void;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import React, { useRef } from "react";
23
import { View, Button } from "react-native";
24
import Pdf from "react-native-pdf";
25
26
export default function PdfWithNavigation() {
27
const pdfRef = useRef<Pdf>(null);
28
29
const goToPage = (page: number) => {
30
try {
31
pdfRef.current?.setPage(page);
32
} catch (error) {
33
console.error("Navigation error:", error);
34
Alert.alert("Error", "Invalid page number");
35
}
36
};
37
38
return (
39
<View style={{ flex: 1 }}>
40
{/* Navigation controls */}
41
<View style={{ flexDirection: "row", justifyContent: "space-around", padding: 10 }}>
42
<Button title="Go to Page 1" onPress={() => goToPage(1)} />
43
<Button title="Go to Page 5" onPress={() => goToPage(5)} />
44
<Button title="Go to Page 10" onPress={() => goToPage(10)} />
45
</View>
46
47
48
ref={pdfRef}
49
source={{ uri: "document.pdf" }}
50
onLoadComplete={(numberOfPages) => {
51
console.log(`PDF loaded with ${numberOfPages} pages`);
52
}}
53
style={{ flex: 1 }}
54
/>
55
</View>
56
);
57
}
58
```
59
60
### Native Props Manipulation
61
62
Direct manipulation of native component properties for advanced use cases.
63
64
```typescript { .api }
65
/**
66
* Set native properties directly on the underlying native component
67
* @param nativeProps - Object containing native properties to set
68
*/
69
setNativeProps(nativeProps: object): void;
70
```
71
72
**Usage Examples:**
73
74
```typescript
75
import React, { useRef, useEffect } from "react";
76
import Pdf from "react-native-pdf";
77
78
export default function AdvancedPdfControl() {
79
const pdfRef = useRef<Pdf>(null);
80
81
const updateNativeProps = () => {
82
// Direct native property manipulation
83
pdfRef.current?.setNativeProps({
84
page: 3,
85
scale: 1.5,
86
// Other native properties as needed
87
});
88
};
89
90
return (
91
92
ref={pdfRef}
93
source={{ uri: "document.pdf" }}
94
onLoadComplete={() => {
95
// Set initial properties after loading
96
setTimeout(() => {
97
updateNativeProps();
98
}, 1000);
99
}}
100
style={{ flex: 1 }}
101
/>
102
);
103
}
104
```
105
106
### Component Reference Management
107
108
Proper component reference handling for programmatic control.
109
110
```typescript { .api }
111
/**
112
* PDF component reference interface
113
* Access to component methods through ref
114
*/
115
interface PdfRef {
116
/** Navigate to specific page */
117
setPage: (pageNumber: number) => void;
118
/** Set native properties */
119
setNativeProps: (nativeProps: object) => void;
120
}
121
```
122
123
**Usage Examples:**
124
125
```typescript
126
import React, { useRef, useImperativeHandle, forwardRef } from "react";
127
import Pdf from "react-native-pdf";
128
129
// Custom PDF wrapper with enhanced control
130
const ControlledPdf = forwardRef<PdfRef, PdfProps>((props, ref) => {
131
const pdfRef = useRef<Pdf>(null);
132
133
useImperativeHandle(ref, () => ({
134
setPage: (pageNumber: number) => {
135
pdfRef.current?.setPage(pageNumber);
136
},
137
setNativeProps: (nativeProps: object) => {
138
pdfRef.current?.setNativeProps(nativeProps);
139
},
140
// Add custom methods
141
goToFirstPage: () => {
142
pdfRef.current?.setPage(1);
143
},
144
goToLastPage: (totalPages: number) => {
145
pdfRef.current?.setPage(totalPages);
146
}
147
}));
148
149
return <Pdf ref={pdfRef} {...props} />;
150
});
151
152
// Usage
153
export default function App() {
154
const pdfRef = useRef<PdfRef>(null);
155
156
return (
157
<ControlledPdf
158
ref={pdfRef}
159
source={{ uri: "document.pdf" }}
160
onPress={() => pdfRef.current?.goToFirstPage()}
161
style={{ flex: 1 }}
162
/>
163
);
164
}
165
```
166
167
### Navigation Utilities
168
169
Helper functions and patterns for common navigation scenarios.
170
171
```typescript { .api }
172
/**
173
* Navigation utility functions
174
* Common patterns for PDF navigation control
175
*/
176
interface NavigationUtils {
177
/** Navigate to next page */
178
nextPage: (currentPage: number, totalPages: number) => void;
179
/** Navigate to previous page */
180
previousPage: (currentPage: number) => void;
181
/** Navigate to first page */
182
goToFirst: () => void;
183
/** Navigate to last page */
184
goToLast: (totalPages: number) => void;
185
/** Navigate by relative offset */
186
navigateBy: (offset: number, currentPage: number, totalPages: number) => void;
187
}
188
```
189
190
**Complete Navigation Example:**
191
192
```typescript
193
import React, { useState, useRef } from "react";
194
import { View, TouchableOpacity, Text, Alert } from "react-native";
195
import Pdf from "react-native-pdf";
196
197
export default function FullNavigationPdf() {
198
const pdfRef = useRef<Pdf>(null);
199
const [currentPage, setCurrentPage] = useState(1);
200
const [totalPages, setTotalPages] = useState(0);
201
202
const navigateToPage = (pageNumber: number) => {
203
if (pageNumber < 1 || pageNumber > totalPages) {
204
Alert.alert("Error", `Page must be between 1 and ${totalPages}`);
205
return;
206
}
207
208
try {
209
pdfRef.current?.setPage(pageNumber);
210
} catch (error) {
211
console.error("Navigation error:", error);
212
Alert.alert("Error", "Failed to navigate to page");
213
}
214
};
215
216
const nextPage = () => {
217
if (currentPage < totalPages) {
218
navigateToPage(currentPage + 1);
219
}
220
};
221
222
const previousPage = () => {
223
if (currentPage > 1) {
224
navigateToPage(currentPage - 1);
225
}
226
};
227
228
const goToFirst = () => navigateToPage(1);
229
const goToLast = () => navigateToPage(totalPages);
230
231
return (
232
<View style={{ flex: 1 }}>
233
{/* Navigation controls */}
234
<View style={{
235
flexDirection: "row",
236
justifyContent: "space-between",
237
alignItems: "center",
238
padding: 10,
239
backgroundColor: "#f0f0f0"
240
}}>
241
<TouchableOpacity
242
onPress={goToFirst}
243
disabled={currentPage === 1}
244
style={{ padding: 8, opacity: currentPage === 1 ? 0.5 : 1 }}
245
>
246
<Text>First</Text>
247
</TouchableOpacity>
248
249
<TouchableOpacity
250
onPress={previousPage}
251
disabled={currentPage === 1}
252
style={{ padding: 8, opacity: currentPage === 1 ? 0.5 : 1 }}
253
>
254
<Text>Previous</Text>
255
</TouchableOpacity>
256
257
<Text>{currentPage} / {totalPages}</Text>
258
259
<TouchableOpacity
260
onPress={nextPage}
261
disabled={currentPage === totalPages}
262
style={{ padding: 8, opacity: currentPage === totalPages ? 0.5 : 1 }}
263
>
264
<Text>Next</Text>
265
</TouchableOpacity>
266
267
<TouchableOpacity
268
onPress={goToLast}
269
disabled={currentPage === totalPages}
270
style={{ padding: 8, opacity: currentPage === totalPages ? 0.5 : 1 }}
271
>
272
<Text>Last</Text>
273
</TouchableOpacity>
274
</View>
275
276
277
ref={pdfRef}
278
source={{ uri: "document.pdf" }}
279
onLoadComplete={(numberOfPages) => {
280
setTotalPages(numberOfPages);
281
console.log(`PDF loaded with ${numberOfPages} pages`);
282
}}
283
onPageChanged={(page, total) => {
284
setCurrentPage(page);
285
}}
286
style={{ flex: 1 }}
287
/>
288
</View>
289
);
290
}
291
```
292
293
### Error Handling for Programmatic Navigation
294
295
Proper error handling when using programmatic navigation methods.
296
297
```typescript { .api }
298
/**
299
* Error handling patterns for navigation
300
* Safe navigation with proper error handling
301
*/
302
interface NavigationErrorHandling {
303
/** Validate page number before navigation */
304
validatePageNumber: (page: number, totalPages: number) => boolean;
305
/** Safe navigation with error handling */
306
safeNavigate: (pdfRef: React.RefObject<Pdf>, page: number) => Promise<boolean>;
307
}
308
```
309
310
**Error Handling Example:**
311
312
```typescript
313
const safeNavigate = async (pdfRef: React.RefObject<Pdf>, pageNumber: number, totalPages: number) => {
314
// Validate inputs
315
if (!pdfRef.current) {
316
console.error("PDF component reference not available");
317
return false;
318
}
319
320
if (typeof pageNumber !== 'number' || isNaN(pageNumber)) {
321
console.error("Invalid page number:", pageNumber);
322
return false;
323
}
324
325
if (pageNumber < 1 || pageNumber > totalPages) {
326
console.error(`Page ${pageNumber} out of range (1-${totalPages})`);
327
return false;
328
}
329
330
try {
331
pdfRef.current.setPage(pageNumber);
332
return true;
333
} catch (error) {
334
console.error("Navigation failed:", error);
335
return false;
336
}
337
};
338
339
// Usage
340
const handleNavigation = async (page: number) => {
341
const success = await safeNavigate(pdfRef, page, totalPages);
342
if (!success) {
343
Alert.alert("Navigation Error", "Could not navigate to the requested page");
344
}
345
};
346
```