reactjsreact-router-domhigher-order-components

Wrapped component not rendering


I am trying to render a component based on a condition. I am using wrapper function to do so. However the component is not rendering when condition is met.

App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Component from "./Component";
import Wrapper from "./Wrapper";
export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/component" element={<Component />} />
        <Route path="/wcomponent" element={Wrapper(Component)} />
      </Routes>
    </BrowserRouter>
  );
}
Wrapper.js
const { useState } = require("react");

const Wrapper = (WrappedComp) => {
  const AuthComponent = (props) => {
    const [value, setValue] = useState(true);
    if (value) return <WrappedComp {...props} />;
    else return <div> The other component </div>;
  };

  return AuthComponent;
};
export default Wrapper;
Component.js
const Component = () => {
  return <div> The first Component </div>;
};

export default Component;

Edit agitated-wind-wlmlcf


Solution

  • If you want to use an Variable as a component wrap it with arrows like

    <Variable />
    

    In this case, your Wrapper is a HOC(Higher order component).

    Basically, you can see it(Wrapper(Component)) is a function with param. All the things you need is define a variable with this Wrapper. and use this variable like a component (component should define in Capitalize form)

    const WrapperComp = Wrapper(Component);
    
    <BrowserRouter>
      <Routes>
        <Route path="/component" element={<Component />} />
        <Route path="/wcomponent" element={<WrapperComp />} />
      </Routes>
    </BrowserRouter>