简体   繁体   中英

How to make a sidebar item behave like a file explorer button in ReactJS?

In my react app, I have a sidebar with Routing functionality. For one of the items on the sidebar, I want it to open the file explorer menu upon clicking. However because of the Routing I am not able to put the file explorer syntax

<input type = "file", name = "file", onChange = {{selectFileHandler}} />

Below are the snippets of my application:

SidebarItems.js

const SidebarItems = [
    {

    {
        name: "Page 1",
        route: '/'
    },
    {
        name: "Load-File",
        route: '/loadfile'
    },

];

export default SidebarItems;

Sidebar.js

const Sidebar = () => {
  const [sidebar, setSidebar] = useState(false);
  
  const showSidebar = () => setSidebar(!sidebar);
  
  return (
    <>
      <IconContext.Provider value={{ color: "#fff" }}>
        <Nav>
          <NavIcon to="#">
            <FaIcons.FaBars onClick={showSidebar} />
          </NavIcon>
          <h1>
            My page
          </h1>
        </Nav>
        <nav>
        
          <ul className='nae-menu-items' onClick={showSidebar}>
            {SidebarData.map((item, index) => {
              return( <li key={index}   />
               <Lint to={item.route}>
               <span>{item.name}</span>
                );
            })}
        </nav>
      </IconContext.Provider>
    </>
  );
};
  
export default Sidebar;

And the Routes.js:

function Routes() {
    return (
        <Router>
            <Switch>
                <Route path="/" exact component={Page1}/>
                <Route path="/loadfile" component={loadfile}/>
               
            </Switch>
        </Router>
    )
}

export default Routes;

How can I modify the loadfile part in the Router to make it behave like a button which will directly open the file explorer?

It's not straightforward, but here's a rough hacked-together demo: https://codesandbox.io/s/stoic-bush-0s6l6

If you click 'Toggle' it mounts a <FilePickOpener /> which should automatically open the dialog:

const FilePickOpener = () => {
  const inputFileRef = useRef(null);
  const onClick = () => {
    inputFileRef.current.click();
  };
  useEffect(() => {
    inputFileRef?.current && inputFileRef.current.click();
  }, [inputFileRef]);

  return (
    <form style={{ visibility: "collapse" }}>
      <input type="file" ref={inputFileRef} />
      <button onClick={onClick}></button>
    </form>
  );
};

Disclaimer : I've only tested on Chrome, it may or may not work on other browsers. Buyer beware.

Update : As feared, it won't work on Safari. Probably a security feature requiring an actual click to initiate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM