I am new to react.
In my app, I have a router component and I am using the render method to pass props. The child component has a wrapper used for authentication.
The problem is that when passing to to the component with the wrapper it has no visibility of the props. Sorry as I am new to this and don't know how to get the props down to to the child component in this situation.
I have created some test classes to illustrate the issue. Once the wrapper is added, I can't access the props, but it works without.
Parent:
import React, { Component } from "react";
import {
Route,
NavLink,
HashRouter
} from "react-router-dom";
import MyComponent from "./mycomponent";
class MyTest extends Component {
// Then we add our constructor which receives our props
constructor(props) {
super(props);
// Next we establish our state
this.state = {
text: "Passing props to components"
}
}
render() {
return (
<HashRouter>
<div>
<NavLink to="/rtest" replace>Route Test</NavLink>
<Route path="/rtest" render={props => (<MyComponent {...props} text={this.state.text}/>)}/>
</div>
</HashRouter>
)
}
}
export default MyTest
Child:
import React, { Component } from "react";
import AuthService from './auth/AuthService';
import withAuth from './auth/withAuth';
const Auth = new AuthService();
class MyComponent extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
console.log(this.props);
}
render() {
return (
<div>
<h2>HELLO</h2>
</div>
);
}
}
export default withAuth(MyComponent);
WithAuth:
import React, { Component } from 'react';
import AuthService from './AuthService';
export default function withAuth(AuthComponent) {
const Auth = new AuthService('http://localhost:8000');
return class AuthWrapped extends Component {
constructor() {
super();
this.state = {
user: null
}
}
componentWillMount() {
//alert(this.props);
if (!Auth.loggedIn()) {
this.props.history.replace('/login')
}
else {
try {
const profile = Auth.getProfile()
this.setState({
user: profile
})
}
catch(err){
Auth.logout()
this.props.history.replace('/login')
}
}
}
render() {
if (this.state.user) {
return (
<AuthComponent history={this.props.history} user={this.state.user} />
)
}
else {
return null
}
}
};
}