Switch between divs when clicking prev/next buttons using React Hooks

Viewed 2045

First of all, I am really new to React, so there is a lot of stuff I have no idea about. But trying to learn I've come across Hooks, which seems really nice for a noob like me. However, my next "project" I am not quite sure about.

Basically I have 4 divs of the same size, but with different content. What I would like to do is to start at the first div (rest not visible), and then in that container I have a "Next" button, if I click that it changes/switches to the second div, which then has a "Prev" and "Next" button, and so on.

I have no idea if that is even possible with Hooks using useState or something like that.

EDIT with example:

So hopefully this illustrates my idea. And this was my initial idea. I think I may be stuck at the return where I am not sure how to actually insert that into the HTML, or what you call it in React-lingo.

const App = ( ) => {

    const initialCount = 0
    const [count, setCount] = useState(initialCount)

    if (count = 0) {
        <div className="box">
            <p>DIV 1</p>
            <div className="btn" onClick={ () => setCount(count + 1) } >Next</div>
        </div>
    } else if (count = 1) {
        <div className="box">
            <p>DIV 2</p>
            <div className="btn" onClick={ () => setCount(count - 1) } >Prev</div>
            <div className="btn" onClick={ () => setCount(count + 1) } >Next</div>
        </div>
    }

    return (
        <div>
           {one of the if-statement elements}
        </div>
    );
};

export default memo(App);
1 Answers

In order to understand this you need to understand how react works, in general to draw/insert HTML elements you must either return it from your function component, or use render class method in your Class component, putting HTML somewhere else will not render them to the page

As for how to achieve this, there are many ways, the simplest for me would be define a set of components you want to render in an array then render them according to the current count number

const App = () => {
    const [count, setCount] = React.useState(0);
    
    const components = [
        <div>1</div>,
        <div>2</div>,
        <div>3</div>,
        <div>4</div>
    ]

    return <div>
        {
            // render component from our components array
            components[count]
        }

        {/* show previous button if we are not on first element */}
        {count > 0 && <button onClick={() => setCount(count - 1)}>prev</button>}

        {/* hide next button if we are at the last element */}
        {count < components.length - 1 && <button onClick={() => setCount(count + 1)}>next</button>}
    </div>
}
Related