How to create tabs of buttons that displays different components onClick with reactjs

Salma mohamed
1 min readNov 4, 2021

Recently, I saw this question on Hackerank, check out the screenshot below.

App.js

import "./styles.css";
import React, { useState } from "react";
import Content from "./Content";
import Content2 from "./Content2";
import Content3 from "./Content3";
export default function App() {
const [active, setActive] = useState("FirstContent");
return (
<div className="App">
<button
className="small-btn outlined"
onClick={() => setActive("FirstContent")}
>
Restart
</button>
<button className="small-btn " onClick={() => setActive("SecondContent")}>
Prev
</button>
<button className="small-btn " onClick={() => setActive("ThirdContent")}>
Next
</button>
{active === "FirstContent" && <Content />}
{active === "SecondContent" && <Content2 />}
{active === "ThirdContent" && <Content3 />}
</div>
);
}

Content.js

import React from "react";
const Content = () => {
return (
<>
<h1>Hello guys you like what you see?</h1>
</>
);
};
export default Content;

Content2.js

import React from "react";
const Content2 = () => {
return (
<>
<h1>content2</h1>
</>
);
};
export default Content2;

Content3.js

import React from "react";
const Content3 = () => {
return (
<>
<h1>content3</h1>
</>
);
};
export default Content3;

Conclusion

Goodluck guys.

--

--