-
Notifications
You must be signed in to change notification settings - Fork 145
Hello! I'm trying to add local search functionality like this example from epub.js, but it seems that it requires access to the book object. Is there some way to get access to that object? Or alternately, is there a better way to do search?
Thanks!
All reactions
Replies: 2 comments 1 reply
@mtnowl You can access book object from renditionRef from below code.
import React, { useState, useRef } from 'react'
import { ReactReader } from 'react-reader'
const App = () => {
// And your own state logic to persist state
const [location, setLocation] = useState(null)
const [firstRenderDone, setFirstRenderDone] = useState(false)
const renditionRef = useRef(null)
const locationChanged = epubcifi => {
// Since this function is also called on initial rendering, we are using custom state
// logic to check if this is the initial render.
// If you block this function from running (i.e not letting it change the page on the first render) your app crashes.
if (!firstRenderDone) {
setLocation(localStorage.getItem('book-progress')) // getItem returns null if the item is not found.
setFirstRenderDone(true)
return
}
// This is the code that runs everytime the page changes, after the initial render.
// Saving the current epubcifi on storage...
localStorage.setItem('book-progress', epubcifi)
// And then rendering it.
setLocation(epubcifi) // Or setLocation(localStorage.getItem("book-progress"))
}
return (
<div style={{ height: '100vh' }}>
<ReactReader
location={location}
locationChanged={locationChanged}
url="https://react-reader.metabits.no/files/alice.epub"
getRendition={rendition => (renditionRef.current = rendition)}
/>
</div>
)
}
export default App
All reactions
I don't see the book object in this code, am I missing something?
All reactions
Hey! I know this thread is a bit old, but I wanted to share an update in case it's still helpful for you or anyone else looking to implement local search with ReactReader.
I recently helped add this functionality, and it's now available as of react-reader@2.0.13! You can perform a local search by passing a query and handling the results via props.
Here’s an example:
<ReactReader
url={DEMO_URL}
title={DEMO_NAME}
location={location}
locationChanged={(loc: string) => setLocation(loc)}
getRendition={(_rendition: Rendition) => {
rendition.current = _rendition
rendition.current.themes.fontSize(largeText ? '140%' : '100%')
}}
searchQuery={searchQuery} // Pass your search term here
onSearchResults={setSearchResults} // Callback to receive search result array
contextLength={2} // Number of characters for context around matches (default is 30)
/>
You’ll need:
A state for searchQuery (your keyword)
A state for searchResults, which will be populated by onSearchResults
This lets you search across the book and receive contextual results with CFIs.
The feature was added in PR #193.