1706105090

Today we're going to create a react js component that displays two tabs


It is often helpful to manage the internal state of a component using the route that displays it. For example, this is a React component that displays two tabs of information: one for /people and one for /offices: ![routing](https://i.ytimg.com/vi/yx5nYOEHBsg/maxresdefault.jpg) ```js import { userState } from 'react' import People from './People' import Offices from './Offices' import '.Aboutt.css' const OldAbout = () => { const [tabId, setTabId] = useState('people') return ( <div className="About"> <div className="About-tabs"> <div onClick={() => setTabId('people')} className={ tabId === 'people' ? 'About-tab active' : 'About-tab' }> People </div> <div onClick={() => setTabId('offices')} className={tabId === 'offices' ? 'About-tab active' : 'About-tab'}>Offices</div> </div></div> {tabId === 'people' && <People />} {tabId === 'offces' && <Offices />} </div> ) } export default OldAbout ``` We are going to move the tabId state from the component into the current browser location. So instead of rendering the component at /about and then using onClick events to change the internal state, we are instead going to have routes to /about/people and /about/offices, which display one tab or the other. The tab selection will survive a browser refresh. We can bookmark the page on a given tab or create a link to a given tab. And we make the tabs actual hyperlinks, which will be recognized as such by anyone navigating with a keyboard or screen reader. What ingredients do we need? Just one: react-router-dom: ``` $ npm install react-router-dom ``` react-router-dom will allow us to synchronize the current browser URL with the components that we render on the screen. When a user clicks a tab, an internal tabId variable is updated, and the People or Offices component is displayed. This guide is for those who are just starting out with react.js and need to make their applications more dynamic. If you liked this post, sign up and leave your comment here, so you can help us grow and provide better content. Thank you

(0) Comments