I have a react app and I want to pass a value (the "groupId") to the main app component.
My app component is defined as function App()
. I tried to pass the parameter value using the following way:
index.tsx:
import React from 'react';
import ReactDOM from 'react-dom';
import './scss/index.scss';
import App from './App';
const targetDivName= 'myapp-ui';
const targetDiv = document.getElementById(targetDivName);
const groupId: string = targetDiv?.getAttribute("data-group-id") ?? '';
ReactDOM.render(
<React.StrictMode>
<App groupId={ groupId } />
</React.StrictMode>,
targetDiv
);
App.tsx:
import React from "react";
import { Box } from "./components/Box";
import styles from './scss/App.module.scss';
function App(groupId: string) {
return (
<div className={ styles.orchestratorUi }>
<Box groupId={ groupId } />
</div>
);
}
export default App;
But this yields the following error (compile and run):
Type '{ groupId: string; }' is not assignable to type 'string'.ts(2322)
How can I pass a value from the HTML code through my App() into the main component (Box
in this example).
You need to change
function App(groupId: string) {
to
function App({groupId}: any) {
or even better to
interface Props {
groupId: string
}
function App({ groupId }: Props) {
What happens with your code is that typescript interprets groupId
in function App(groupId: string) {
to be of type string
, and instead receives an object when you instanciate App
.
In your case, this object is {"groupId": groupId}
where groupId
here is the variable you assigned in App.tsx
.