Languages
[Edit]
EN

React - navbar with flexbox

5 points
Created by:
chelsea
356

In this article, we would like to show you how to create navbar with flexbox in React.

In below example, we create a simple Navbar component as a flex container with four flex items (children).

Navbar container uses (navbarStyle):

  • display: flex style which enables a flex context for all its direct children,
  • position: fixed¬†with coordinates set to 0 makes¬†element stretched and located always on¬†the top of the webpage.

Children properties:

  • flex: 1¬†style¬†determines how much of the available space¬†each flexible element will occupy (in our case the spacer will occupy as much space as possible, stretching elements to the sides),
  • flex: none¬†style¬†makes item width¬†fit to content.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const navbarStyle = {
    position: 'fixed',
    top: '0',
    left: '0',
    right: '0',
  	display: 'flex' // <---------- required
}

const sideMenuStyle = {
    padding: '5px',
    background: '#aacdd2',
    flex: 'none'
}

const linksStyle = {
    padding: '5px',
    background: '#ddf9c4',
    flex: 'none'
}

const linkStyle = {
    padding: '0 5px'
}

const spacerStyle = {
    background: '#fff9c4',
  	flex: '1' // <----------------- to fill empty navbar space
}

const userMenuStyle = {
    padding: '5px',
    background: '#bbdefb',
    flex: 'none'
}

const Navbar = () => {
    return (
        <div style={navbarStyle}>
            <div style={sideMenuStyle}>
                <button>Menu</button>
            </div>
            <div style={linksStyle}>
                <a style={linkStyle} href='#'>Home</a>
                <a style={linkStyle} href='#'>Gallery</a>
                <a style={linkStyle} href='#'>About</a>
            </div>
            <div style={spacerStyle}></div>
            <div style={userMenuStyle}>
                <button>Login</button>
                <button>Sign Up</button>
            </div>
        </div>
    );
};

const App = () => {
    return (
        <div style={{padding: '30px 0 0 0', height: '100px'}}>
		  <Navbar/>
          <div>Place to web page body...</div>
        </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

CSS - Flexbox

Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join