0

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

tanmay196
  • 15
  • 6

1 Answers1

1

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>
thienms98
  • 167
  • 1
  • 10
  • I actually tried using variable but I wrote the variable name in lowercase. For the first time I realized that components have to be named in capitalized format. Otherwise I used to think that is just a convention. – tanmay196 Jun 13 '23 at 08:08
  • Yes, always using component in capitalize case. (y) – thienms98 Jun 13 '23 at 08:11