I have simple react-application:
export default class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<Header/>
<Switch>
<Route exact path="/" component={MainPage}/>
<AdminLayout>
<Route exact path="/admin" component={AdminPage}/>
<Route exact path="/admin/add-user" component={AddUserPage}/>
</AdminLayout>
<Route path="/sign-up" component={SignUpPage}/>
<Route path="*" component={NotFound}/>
</Switch>
</Router>
</Provider>
);
}
}
Here I needed Layout component for admin components. I wrapped them in it:
export default class AdminLayout extends React.Component<{ }, AdminLayoutState> {
state: AdminLayoutState = {
contentType: "personal"
};
setActiveMenuItem = (contentType: string) => {
this.setState({
contentType: contentType
});
};
render() {
const {
contentType
} = this.state;
return (
<Fragment>
<Segment size={"huge"}>
<Grid>
<Grid.Row>
<Grid.Column width={3}>
<MenuLeft
contentType={contentType}
onClick={(contentType) => this.setActiveMenuItem(contentType)}
/>
</Grid.Column>
<Grid.Column width={12}>
{
React.Children.map(this.props.children, function (child) {
// @ts-ignore
return React.cloneElement(child, {})
})
}
</Grid.Column>
</Grid.Row>
</Grid>
</Segment>
</Fragment>
);
}
}
I need to access layout params like contentType:
export default class AdminPage extends React.Component<AdminPageProps, AdminPageState> {
constructor(props: AdminPageProps) {
super(props);
// const dispatch = useDispatch();
}
state: AdminPageState = {
// optional second annotation for better type inference
columnNames: [
"first name",
"last name",
"mail",
"actions"
],
};
render() {
const {
columnNames,
} = this.state;
const {
contentType
} = this.props;
return (
<>
<Header>
HEADER
{contentType}
</Header>
<Divider/>
<Button primary floated={"right"}>
Add
</Button>
<UsersTable
color={"blue"}
tableType={"doctor"}
recordsLimit={50}
columnNames={columnNames}
/>
</>
);
}
}
But I get error, that propert does not exist. Then I changed child pass in Layout to:
return React.cloneElement(child, this.props)
And get Uncaught TypeError: Cannot read property 'props' of undefined
I supposed that my wrapper will get params from parent components and I will be able to access its state from child components like AdminPage, AddUserPage. Unfortunately no. How can I perform such wrapper and pass props to childs properly?