I would like to display a button only if there is history.
Is this the correct way to do it?
browserCheck.jsx helper identifies the browser and version
const browserCheck = (function () {
const { userAgent } = navigator; let browserNumber; let M = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
browserNumber = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
return `IE ${browserNumber[1] || ''}`;
}
if (M[1] === 'Chrome') {
browserNumber = userAgent.match(/\b(OPR|Edge?)\/(\d+)/);
if (browserNumber != null) return browserNumber.slice(1).join(' ').replace('OPR', 'Opera').replace('Edg ', 'Edge ');
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((browserNumber = userAgent.match(/version\/(\d+)/i)) != null) M.splice(1, 1, browserNumber[1]);
return M.join(' ');
}());
export default browserCheck;
browserHistory.jsx sets the initial history length based on the browser
import browserCheck from './browserCheck';
const browserHistory = (function () {
const browsers = ['chrome', 'safari', 'firefox', 'msie', 'opera'];
let currentBrowser;
browsers.forEach((browser) => {
if (browserCheck.toLowerCase().indexOf(browser) !== -1) {
currentBrowser = browser;
}
});
// Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1.
// Refer to: https://www.w3schools.com/jsref/prop_his_length.asp
let initialValue = 0;
if (currentBrowser === 'chrome') initialValue = 1;
if (currentBrowser === 'firefox') initialValue = 1;
if (currentBrowser === 'Safari') initialValue = 1;
return initialValue;
}());
export default browserHistory;
component.jsx
{(history.length > browserHistory) ?
<button
className={css.backButton}
onClick={history.goBack}
style={{ color: theme.bodyColour }}
><Back</button> :
null
}
UPDATE:
please see: w3schools.com/jsref/prop_his_length.asp
Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1
NEW UPDATE: helpers added. browserHistory contains the default browser history length to compare against.