I'm new to react and am building a basic react app and have just built a basic area where navigation links render on a page but wonder whether my current start could be optimised - for example, I wonder whether an area like this:
render() {
return (
<Root navLinks={this.state.navLinks}></Root>
);
}
Could be changed to something like this:
render() {
return (
<Root>
<NavLinks navLinks={this.state.navLinks} />
</Root>
);
}
And I wonder about other aspects of the app such as do I need an App.js file or index.js file and could have one rather than the other?
Any quick basic beginner advice would be much appreciated. The code can be better found in this Stackblitz demo or below:
App.js:
import React, {Component} from "react";
import {navLinks} from "./components/nav-links";
import Root from "./components/Root";
export default class App extends Component {
constructor() {
super();
this.state = {
navLinks: navLinks
}
}
render() {
return (
<Root navLinks={this.state.navLinks}></Root>
);
}
}
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
/components/Root.js:
import React from "react";
import NavMenu from "./nav-menu";
import BodyCode from "./body-code";
export default class Root extends React.Component {
render() {
return (
<div id="container">
<div id="header">
<NavMenu navLinks={this.props.navLinks} />
</div>
<div id="body">
<BodyCode />
</div>
</div>
)
}
}
/components/body-code.js:
import React from "react";
export default class bodyCode extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true}; // boolean for event listener alternative
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
} // bind is saying make the ‘this’ keyword bind(this), where the 2nd ‘this’ is the ‘this’ of the constructor
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn // sets state to the opposite of whatever it is
}));
}
render() {
return (
<div>
<p>some body text</p>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
</div>
)
}
}
/components/nav-links.js:
export const navLinks = [
{
name: "home",
href: "/"
},
{
name: "subs",
href: "/subs"
}
];
/components/nav-menu.js:
import React from "react";
export default class navBar extends React.Component {
render() {
return (
this.props.navLinks.map((link) => <a href={link.href} key = {link.href} > {link.name} </a>)
)
}
}