Reputation: 121
In react, when I pass information from App component to App2 component as
<App2 value = {this.state.name}/>
it works well, but when I try to pass information from App2 component to App1 component as
<App1 value = {this.state.name2}/>
inside the render function of App2 component , it gives an error :-
[ts] 'render' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
The code for App1 component is :-
import * as React from "react";
import App2 from './App2';
interface IState{
name : string,
age : 5;
}
interface Iprops{
value ? : any
}
class App extends React.Component<Iprops,IState>{
constructor(props:any)
{
super(props);
this.state = {
age : 5,
name : ""
}
this.change = this.change.bind(this);
}
public change(event : any){
// alert("you have submitted the form");
this.setState({
name : event.target.value
});
}
public render()
{
return(
<div>
<input type="text" value = {this.state.name} onChange = {this.change}/>
<App2 value = {this.state.name}/>
</div>
)
}
}
export default App;
and App2 component code is :-
import * as React from "react";
import App from './App'
interface Iprops{
value ? : any;
}
interface Istate{
name2 : string
}
class App2 extends React.Component<Iprops,Istate>{
constructor(props:any)
{
super(props);
this.state = {
name2 : " "
}
}
public change(event : any){
this.setState({name2 : event.target.value})
}
public render() {
return (
<div>
<h4>
<input type="text" value = {this.props.value} onChange = {this.change}/>
Hello, I am in App3 component.
<App value = {this.state.name2}/>
</h4>
</div>
)
}
}
export default App2;
Is there any other method to pass the information vice-versa between components in react using typescript.
Upvotes: 1
Views: 416
Reputation: 1991
Note, that you have circular dependency between App
and App2
. Typescript is unable to infer return type of App2#render
as it uses App
in it's return expression which in turn uses App2
which isn't yet fully defined ...
Long story short - declare your render methods as follows:
public render(): JSX.Element {
// ...
}
Thanks to this Typescript compiler knows render
signature without looking at function contents.
Upvotes: 2