I am new to using React, I have a basic understanding of JavaScript. I have created this Web App in JavaScript before but I am recreating it in React for practice.
Here is the Original Web App: https://iamstevenhale.github.io/DrunkenHeroes/menu.html
I am trying to have the 'Disclaimer' Component displayed when the user clicks on the component button and then close again when they click on the X.
What is the correct way to navigate between pages when clicking on buttons?
Is my setup wrong?
INDEX.js
import React from 'react'
import ReactDOM from 'react-dom'
import 'bootstrap/dist/css/bootstrap.css'
import Menu from './components/menu'
ReactDOM.render(<Menu />, document.getElementById('root'))
MENU.js (Component)
import Disclaimer from './disclaimer'
import './styles.css'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
class Menu extends React.Component {
constructor(props) {
super(props)
this.state = {
showComponent: false,
}
this._onButtonClick = this._onButtonClick.bind(this)
}
_onButtonClick() {
this.setState({
showComponent: true,
})
}
render() {
return (
<div>
<div>
<h1 className='title sway'>Drunken Heroes</h1>
</div>
<div className='centreDivContents'>
<p className='subtitle'>What happens when Heroes Party?</p>
</div>
<div className='centreDivContents'>
<button className='HSButton'>Play</button>
<br />
<button className='HSButton'>Rules</button>
<br />
<div>
<button className='HSButton' onClick={this._onButtonClick}>
Disclaimer
</button>
{this.state.showComponent ? <Disclaimer /> : null}
</div>
</div>
</div>
)
}
}
export default Menu
DISCLAIMER.js (component)
import React from 'react'
import 'bootstrap/dist/css/bootstrap.css'
import './styles.css'
class Disclaimer extends React.Component {
render() {
return (
<div>
<div>
<h1>X</h1>
</div>
<h1>Disclaimer - Input the disclaimer text here.</h1>
</div>
)
}
}
export default Disclaimer
1) You can create a method hideDisclaimer and set the state showComponent to false as:
hideDisclaimer = () => {
this.setState({
showComponent: false,
});
};
Live Demo
and pass the method as a prop
{this.state.showComponent ? (
<Disclaimer hideDisclaimer={this.hideDisclaimer} />
) : null}
and set onClick listener on the button as, I've made the h1 to button:
<button onClick={this.props.hideDisclaimer}>X</button>
2) You can create _onButtonClick method generic and pass the state as an argument and set the state as the parameter as:
_onButtonClick(state) {
this.setState({
showComponent: state,
});
}
Live Demo
and pass the same method as:
{this.state.showComponent ? (
<Disclaimer _onButtonClick={this._onButtonClick} />
) : null}
and onClick of the X button then you can invoke the method as:
<button onClick={() => this.props._onButtonClick(false)}>X</button>