uptick / react-keyed-file-browser

Folder based file browser given a flat keyed list of objects, powered by React.
MIT License
298 stars 144 forks source link

How can I programmatically select a file? #153

Closed jestrickler closed 3 years ago

jestrickler commented 3 years ago

I am using react-keyed-file-browser@1.6.1. What I'd like to do is if the url specifies a particular file ('/files/{id}') show the file-browser with that file pre-selected as if all containing folders and the file itself had been clicked:

Screen Shot 2020-10-30 at 1 26 34 PM
mwfister commented 3 years ago

I don't believe we expose the FileBrowser methods needed to achieve this. So we don't officially support this. Regardless, you can use refs to access the FileBrowser and call these methods imperatively.

Some things to note:

The below should work for you if you want to preview it in storybook:

class OpenFile extends React.Component {
  fileBrowserRef = null

  componentDidMount() {
    if (this.fileBrowserRef) {
      this.fileBrowserRef.child.openFolder('animals/')
      this.fileBrowserRef.child.openFolder('animals/pets/')
      this.fileBrowserRef.child.select('animals/pets/dog.png', 'file')
      this.fileBrowserRef.child.preview(
        this.fileBrowserRef.child.getFile('animals/pets/dog.png'),
      )
    }
  }

  render() {
    return (
      <FileBrowser
        ref={el => { this.fileBrowserRef = el }}
        files={[
          {
            key: 'animals/',
            modified: +Moment().subtract(1, 'hours'),
            size: 0,
          },
          {
            key: 'animals/pets/',
            modified: +Moment().subtract(1, 'hours'),
            size: 0,
          },
          {
            key: 'animals/pets/dog.png',
            modified: +Moment().subtract(1, 'hours'),
            size: 48 * 1024,
          },
          {
            key: 'elephant.png',
            modified: +Moment().subtract(3, 'days'),
            size: 52 * 1024,
          },
        ]}
      />
    )
  }
}
storiesOf('FileBrowser', module)
  .add('Open File programatically', () => <OpenFile />)
baur commented 2 years ago

@mwfister

I got an error:

ncaught TypeError: Cannot read properties of undefined (reading 'openFolder')
    at OpenFile.componentDidMount (OpenFile.jsx:10:1)
    at commitLifeCycles (react-dom.development.js:20663:1)
    at commitLayoutEffects (react-dom.development.js:23426:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at commitRootImpl (react-dom.development.js:23151:1)
    at unstable_runWithPriority (scheduler.development.js:468:1)
    at runWithPriority$1 (react-dom.development.js:11276:1)
    at commitRoot (react-dom.development.js:22990:1)
baur commented 2 years ago

How can I do that via useRef?