Im trying to access a components state from another component with not much of a success. So far my code looks like this:
The two components are rendered in App.js, the entry file. First components is a mobile navigation. That one should be open/closed depending on the state in component 2 wich is a toggle-button. Can anyone help me out?
Component 1.(In here i want to access the state of 'toggled' from component 2)
import * as style from './MobileNavigation.style'
import React, { Component } from 'react'
import Button from '../../components/Button'
class MobileNavigation extends Component {
render() {
return (
<style.Background>
<style.Menu>
<style.MenuItem>
<style.RouterLink to="home">home</style.RouterLink>
</style.MenuItem>
<style.MenuItem>
<style.RouterLink to="about">about</style.RouterLink>
</style.MenuItem>
<style.MenuItem>
<style.RouterLink to="contact">contact</style.RouterLink>
</style.MenuItem>
</style.Menu>
</style.Background>
)
}
}
export default MobileNavigation
Component 2
import React, { Component } from 'react'
import styled from 'styled-components'
import * as style from './Hamburger.style'
interface Props {
width: string
height: string
fill: string
toggled?: boolean
}
interface State {
toggled?: boolean
}
const Svg = styled.svg`
width: ${(props: Props) => props.width};
height: ${(props: Props) => props.height};
`
class Hamburger extends Component<Props, State> {
static defaultProps = {
width: '100%',
height: '100%',
fill: '#172b41',
toggled: true
}
constructor(props: any) {
super(props)
this.state = {
toggled: true
}
}
onClick(toggled: boolean) {
this.setState({
toggled: !this.state.toggled,
})
}
render() {
return (
<style.Wrapper onClick={this.onClick.bind(this, this.props.toggled)}>
{this.state.toggled ? (
<div>closed</div>
) : (
<div>open</div>
)}
</style.Wrapper>
)
}
}
export default Hamburger