or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-react-lazy-load

React component for lazy loading content using the Intersection Observer API

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/react-lazy-load@4.0.x

To install, run

npx @tessl/cli install tessl/npm-react-lazy-load@4.0.0

0

# React Lazy Load

1

2

React Lazy Load is a React component for lazy loading content using the modern Intersection Observer API. It allows developers to defer loading of images and other content until they are about to become visible in the viewport, improving page performance and user experience. The component supports configurable offset margins, visibility thresholds, and custom styling through CSS classes.

3

4

## Package Information

5

6

- **Package Name**: react-lazy-load

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install react-lazy-load`

10

11

## Core Imports

12

13

```typescript

14

import LazyLoad from "react-lazy-load";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const LazyLoad = require("react-lazy-load");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import React from 'react';

27

import LazyLoad from 'react-lazy-load';

28

29

const MyComponent = () => (

30

<div>

31

<LazyLoad height={762}>

32

<img src='https://example.com/image.jpg' alt="Lazy loaded image" />

33

</LazyLoad>

34

</div>

35

);

36

```

37

38

## Architecture

39

40

React Lazy Load is built around the Intersection Observer API and consists of:

41

42

- **LazyLoad Component**: A class-based React component that wraps content to be lazy loaded

43

- **Intersection Observer**: Modern browser API for efficient viewport intersection detection

44

- **Scroll Parent Detection**: Utility function to find the nearest scrollable container

45

- **CSS Classes**: Applied dynamically to enable custom styling and transitions

46

47

## Capabilities

48

49

### LazyLoad Component

50

51

A React class component that wraps content and defers its rendering until it becomes visible in the viewport.

52

53

```typescript { .api }

54

/**

55

* React component for lazy loading content using Intersection Observer API

56

* @param props - Component properties defining behavior and styling

57

*/

58

declare class LazyLoad extends React.Component<Props, State> {

59

static defaultProps: {

60

elementType: string;

61

className: string;

62

offset: number;

63

threshold: number;

64

width: null;

65

onContentVisible: null;

66

height: null;

67

};

68

69

/** Intersection observer instance used for detecting visibility */

70

elementObserver: IntersectionObserver | null;

71

/** React ref to the wrapper element */

72

wrapper: React.RefObject<React.Component> | null;

73

74

constructor(props: Props);

75

componentDidMount(): void;

76

shouldComponentUpdate(_: Props, nextState: State): boolean;

77

componentWillUnmount(): void;

78

getEventNode(): Window | HTMLElement;

79

lazyLoadHandler: (entries: IntersectionObserverEntry[]) => void;

80

render(): React.ReactElement;

81

}

82

83

interface Props {

84

/** Content to be lazy loaded (required) */

85

children: React.ReactNode;

86

/** Additional CSS class names to apply to the wrapper element */

87

className?: string;

88

/** HTML element type to render as wrapper (default: 'div') */

89

elementType?: string;

90

/** Height of the placeholder element before content loads */

91

height?: string | number;

92

/** Viewport offset for triggering load - can be number (pixels) or string (CSS margin format) */

93

offset?: string | number;

94

/** Visibility threshold (0-1) - fraction of element that must be visible to trigger loading */

95

threshold?: number;

96

/** Width of the placeholder element before content loads */

97

width?: number | string;

98

/** Callback function executed when content becomes visible */

99

onContentVisible?: () => void;

100

}

101

102

interface State {

103

/** Whether content is visible and should be rendered */

104

visible: boolean;

105

}

106

```

107

108

### Public Instance Methods

109

110

Public methods available on LazyLoad component instances.

111

112

```typescript { .api }

113

/**

114

* Gets the scroll parent element for the LazyLoad wrapper

115

* @returns The nearest scrollable ancestor element or window if none found

116

*/

117

getEventNode(): Window | HTMLElement;

118

119

/**

120

* Intersection Observer callback handler for visibility detection

121

* @param entries - Array of intersection observer entries from the browser API

122

*/

123

lazyLoadHandler: (entries: IntersectionObserverEntry[]) => void;

124

```

125

126

**Method Usage Examples:**

127

128

```typescript

129

import React, { useRef } from 'react';

130

import LazyLoad from 'react-lazy-load';

131

132

const ExampleWithRef = () => {

133

const lazyLoadRef = useRef<LazyLoad>(null);

134

135

const handleClick = () => {

136

// Access public methods via component ref

137

if (lazyLoadRef.current) {

138

const scrollParent = lazyLoadRef.current.getEventNode();

139

console.log('Scroll parent:', scrollParent);

140

}

141

};

142

143

return (

144

<div>

145

<button onClick={handleClick}>Get Scroll Parent</button>

146

<LazyLoad ref={lazyLoadRef} height={400}>

147

<img src="https://example.com/image.jpg" alt="Example" />

148

</LazyLoad>

149

</div>

150

);

151

};

152

```

153

154

**Component Usage Examples:**

155

156

```typescript

157

import React from 'react';

158

import LazyLoad from 'react-lazy-load';

159

160

// Basic image lazy loading

161

const BasicExample = () => (

162

<LazyLoad height={400}>

163

<img src="https://example.com/large-image.jpg" alt="Description" />

164

</LazyLoad>

165

);

166

167

// Load with 300px offset before visible

168

const OffsetExample = () => (

169

<LazyLoad height={400} offset={300}>

170

<img src="https://example.com/image.jpg" alt="Description" />

171

</LazyLoad>

172

);

173

174

// Load only when 95% visible with callback

175

const ThresholdExample = () => (

176

<LazyLoad

177

height={400}

178

width={600}

179

threshold={0.95}

180

onContentVisible={() => console.log('Image loaded!')}

181

>

182

<img src="https://example.com/image.jpg" alt="Description" />

183

</LazyLoad>

184

);

185

186

// Custom wrapper element and styling

187

const CustomWrapperExample = () => (

188

<LazyLoad

189

elementType="section"

190

className="custom-lazy-wrapper"

191

height={300}

192

>

193

<div>

194

<h3>Lazy loaded content</h3>

195

<p>This content loads when it becomes visible.</p>

196

</div>

197

</LazyLoad>

198

);

199

```

200

201

### CSS Classes

202

203

The component applies CSS classes automatically for styling and transitions.

204

205

```css { .api }

206

/* Base class applied to all LazyLoad wrapper elements */

207

.LazyLoad {

208

/* Custom styles here */

209

}

210

211

/* Added when content becomes visible */

212

.LazyLoad.is-visible {

213

/* Visible state styles here */

214

}

215

216

/* Example transition effect */

217

.LazyLoad {

218

opacity: 0;

219

transition: all 1s ease-in-out;

220

}

221

222

.LazyLoad.is-visible {

223

opacity: 1;

224

}

225

```

226

227

## Configuration Options

228

229

### Offset Configuration

230

231

The `offset` prop controls when loading is triggered relative to the viewport:

232

233

```typescript

234

// Number: pixels offset in all directions

235

<LazyLoad offset={100}>Content</LazyLoad>

236

237

// String: CSS margin format (top right bottom left)

238

<LazyLoad offset="100px 0px 200px 50px">Content</LazyLoad>

239

240

// String: Single value for all sides

241

<LazyLoad offset="150px">Content</LazyLoad>

242

```

243

244

### Threshold Configuration

245

246

The `threshold` prop controls how much of the element must be visible:

247

248

```typescript

249

// 0: Load as soon as any part is visible (default)

250

<LazyLoad threshold={0}>Content</LazyLoad>

251

252

// 0.5: Load when 50% is visible

253

<LazyLoad threshold={0.5}>Content</LazyLoad>

254

255

// 1.0: Load only when completely visible

256

<LazyLoad threshold={1.0}>Content</LazyLoad>

257

```

258

259

**Note**: When using threshold values > 0, you must specify both `width` and `height` props for the browser to calculate the viewable area correctly.

260

261

### Element Type Configuration

262

263

Customize the wrapper HTML element:

264

265

```typescript

266

// Default div wrapper

267

<LazyLoad>Content</LazyLoad>

268

269

// Custom element types

270

<LazyLoad elementType="section">Content</LazyLoad>

271

<LazyLoad elementType="article">Content</LazyLoad>

272

<LazyLoad elementType="span">Content</LazyLoad>

273

```

274

275

## Error Handling

276

277

The component gracefully handles various scenarios:

278

279

- **Missing Intersection Observer**: Falls back to immediate loading on older browsers

280

- **Invalid threshold values**: Clamps to 0-1 range

281

- **Missing width/height with threshold**: Uses element's natural dimensions when possible

282

- **Component unmounting**: Automatically cleans up observers to prevent memory leaks

283

284

## Performance Considerations

285

286

- **One-time loading**: Content is loaded only once and observers are cleaned up immediately

287

- **Automatic cleanup**: Intersection observers are properly disposed when components unmount

288

- **Minimal re-renders**: Component only re-renders when visibility state changes from false to true

289

- **Native efficiency**: Uses browser-native Intersection Observer for optimal performance