In order to study the react framework, I've been developing a simple web application to rate books. It's currently looking like this:
And the idea of the side bar is simple enought: it's width will be 0 when hidden, and when I click a open menu button it will be set to another width.
The code behind it all is looking like this:
import React from 'react';
import { Link } from 'react-router-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import home from '../../image/side-nav/home.png';
import list from '../../image/side-nav/list.png';
import '../../css/SideNavBar.css'
import * as utils from '../../scripts/utils.js';
const SideNavBar = () =>{
return(
<Router>
<div>
<span className="spanOpen" onClick={utils.openNav()}>☰</span>
<div className="sidenav">
<a className='closebtn' onClick={utils.closeNav()}>×</a>
<ul>
<li>
<Link to='/'><img src={home} alt='Home' /><span className='h-item'>Home</span></Link>
</li>
<li>
<Link to='/books'><img src={list} alt='Books' /><span className='b-item'>Books</span></Link>
</li>
</ul>
<div className='sidenav-footer'>
<hr />
<small>Pelicer © 2018</small>
</div>
</div>
</div>
</Router>
);
}
export default SideNavBar;
And here is the code of the util.js file, which contains the the fucntions to change:
export function openNav() {
// document.getElementsByClassName("sidenav")[0].style.width = "315px";
}
export function closeNav() {
// document.getElementsByClassName("sidenav")[0].style.width = "0";
}
But when I run it, I get the error: TypeError: Cannot read property 'style' of undefined. It happens because it is trying to change the width of somethings that has not yet been created. What I want to do, and tried using componentDidMount, is to import the JavaScript after the HTML has been rendered, in a way that when it sets the width, the component is already there. Can someone help out in a solution?
