Answer the question
In order to leave comments, you need to log in
How to properly type in React.js (React.cloneElement)?
Hello. I am rewriting a small functionality in TypeScript. Tell me how to optimize (make it better). Emphasis on the following points:
https://codepen.io/dc65k/pen/poEPKqM
{
React.cloneElement(
children as unknown as JSX.Element,
{...this.state}
)
}
import React, { Component, PureComponent, ReactNode } from 'react';
import logo from './logo.svg';
import './App.css';
import { render } from '@testing-library/react';
type ITodos = {
completed: boolean;
id: number;
title: string;
userId: number
}
// interface ITodos {
// completed: boolean;
// id: number;
// title: string;
// userId: number
// }
type TwitterState = {
todos: ITodos[]
}
type TwitterProps = {
username: string,
children: React.ReactNode
}
type UserProfileProps = {
todos?: ITodos[]
}
class Twitter extends PureComponent<TwitterProps, TwitterState> {
state = {
todos: []
}
async componentDidMount() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json());
console.log(response);
this.setState({
todos: response
});
}
render() {
const {
children
} = this.props;
const {
todos
} = this.state;
return (
<React.Fragment>
{
React.cloneElement(
children as unknown as JSX.Element,
{...this.state}
)
}
</React.Fragment>
)
}
}
const UserProfile = (props: UserProfileProps) => {
const { todos } = props;
return (
<React.Fragment>
{
todos ? <h2>UserProfile</h2> : <div>Loading...</div>
}
</React.Fragment>
)
}
class App extends Component {
render() {
return (
<div className="App">
<Twitter username='user1'>
<UserProfile />
</Twitter>
</div>
);
}
}
export default App;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question