Single Page Application in React without React-Router

Viewed 42

I'm trying to build my first single page application using React. I would like to build the web application without using any external libraries, such as React-Router. Also, I don't know if this is important to note, but I'm using React over a CDN.

I'm having a hard time finding how to hide and show components on different levels in React. Here is the overall structure of the application:

dashboard.html

...

<div id="content"> </div>

...

dashboard.js

document.addEventListener(
  "DOMContentLoaded",
  ReactDOM.render(<App />, document.querySelector("#content"))
);


function App() {
  return (
    <div>
      <AccountView />
      <PersonsView />
    </div>
  );
}

function AccountView() {
  return (
    <div>
      Foo
    </div>
  );
}

function PersonsView() {
  return (
    <div>
      <Persons />
      <AddPersonForm />
      <button id="showAccountView">Show Account View</button>
    </div>
  );
}

function Persons() {
  return (
    <div>
      Foo
    <button id="showAddPersonForm">Show Add Person Form</button>
    </div>
  );
}

function AddPersonsForm() {
  return (
    <form>
      Bar
    </form>
  );
}

In <App /> I would like to only show the <PersonsView />, only when clicking the button (#showAccountView), the <PersonsView /> should be hidden and the <AccountView /> shown.

Then in <PersonsView />, I would like to only show the <Persons />, only when clicking the button (#showAddPersonForm), the <Persons /> should be hidden and the <AddPersonForm /> shown.

1 Answers

having a state in your App() can handle the visibility of components. Here is an exemplaric untested implementation:

function App() {
    const [location, setLocation] = useState('AccountView');
    return (
        <div>
            {location === 'AccountView' && <AccountView />}
            {location === 'PersonsView' && <PersonsView />}
            <Button
                onPress={() => {
                    setLocation(
                        location === 'AccountView'
                            ? 'PersonsView'
                            : 'AccountView',
                    );
                }}
            />
        </div>
    );
}

you can use props to pass the setLocation function to the views or create a context for your app

example how to pass props:

// call the account view like this
<AccountView setLocation={setLocation} />;

// and modify the account view like this
function AccountView({ setLocation }) {
    return (
        <div>
            <button onPress={() => setLocation('yourDestination')}>
                YourButtonText
            </button>
        </div>
    );
}
Related