Reputation: 9844
I have a MovieSearch
component:
render() {
const greeting = 'Welcome to React'
return (
<React.Fragment>
<SearchAPI />
<SearchAPIResults message={greeting}/>
</React.Fragment>
)
}
Which passes a string prop to it's child SearchAPIResults
component:
// works
function SearchAPIResults(props) {
return (
<h1>{props.message}</h1>
);
}
// does not work
// class SearchAPIResults extends React.Component {
// constructor(props) {
// super(props)
// this.state = {message: props.message}
// }
// }
The top code segment works. If I try the bottom code I get a message in my MovieSearch
component:
Type '{ message: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. Property 'message' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
I know there's a difference between Class and Function components and I think the SearchAPIResults
component should be a Function component since it's only displaying some data. But I'm still wondering how I would pass props between 2 Class components.
Upvotes: 2
Views: 1405
Reputation: 11591
Looks like you're using TypeScript. In that case you have to tell TS what the structure of your component props is. Otherwise it doesn't know what the type of the message
prop is supposed to be. You can do so if you're using either functional or class components, but the syntax will be a little different:
type Props = {
message: string;
};
const SearchAPIResults: React.FC<Props> = (props) {
return (
<h1>{props.message}</h1>
);
}
or
type Props = {
message: string;
};
class SearchAPIResults extends React.Component<Props> {
constructor(props) {
super(props)
this.state = {message: props.message}
}
render() {
return (
<h1>{this.state.message}</h1>
);
}
}
Edit: as a side note, doing this:
this.state = {message: props.message}
is generally an anti-pattern in React and you should avoid it. Don't use props to set the state of your component - doing so creates conflict and confusion as to what the "source of truth is" for the data in your app. If the message
prop changes, your child component won't properly update because the value stored in state
has become stale. Just read the message
prop directly and don't store it in state.
class SearchAPIResults extends React.Component<Props> {
render() {
return (
<h1>{this.props.message}</h1>
);
}
}
Upvotes: 4