EN
React - navbar with flexbox
5 points
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 to0
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 thespacer
will occupy as much space as possible, stretching elements to the sides),flex: none
style makes item width fit to content.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const navbarStyle = {
6
position: 'fixed',
7
top: '0',
8
left: '0',
9
right: '0',
10
display: 'flex' // <---------- required
11
}
12
13
const sideMenuStyle = {
14
padding: '5px',
15
background: '#aacdd2',
16
flex: 'none'
17
}
18
19
const linksStyle = {
20
padding: '5px',
21
background: '#ddf9c4',
22
flex: 'none'
23
}
24
25
const linkStyle = {
26
padding: '0 5px'
27
}
28
29
const spacerStyle = {
30
background: '#fff9c4',
31
flex: '1' // <----------------- to fill empty navbar space
32
}
33
34
const userMenuStyle = {
35
padding: '5px',
36
background: '#bbdefb',
37
flex: 'none'
38
}
39
40
const Navbar = () => {
41
return (
42
<div style={navbarStyle}>
43
<div style={sideMenuStyle}>
44
<button>Menu</button>
45
</div>
46
<div style={linksStyle}>
47
<a style={linkStyle} href='#'>Home</a>
48
<a style={linkStyle} href='#'>Gallery</a>
49
<a style={linkStyle} href='#'>About</a>
50
</div>
51
<div style={spacerStyle}></div>
52
<div style={userMenuStyle}>
53
<button>Login</button>
54
<button>Sign Up</button>
55
</div>
56
</div>
57
);
58
};
59
60
const App = () => {
61
return (
62
<div style={{padding: '30px 0 0 0', height: '100px'}}>
63
<Navbar/>
64
<div>Place to web page body...</div>
65
</div>
66
);
67
};
68
69
const root = document.querySelector('#root');
70
ReactDOM.render(<App />, root);