React Custom Component Parameter Is Not Defined - reactjs

I'm currently using the Typescript version of reactjs and keep getting the error "message is not defined".
This error is coming from line 5.
import './App.css'
import * as React from "react";
const MyComponent: React.FC = ({ message: string }) => {
return <h1>{message}</h1>
}
export default function App() {
return (
<div className="app">
<MyComponent message="hello world"></MyComponent>
</div>
);
}

You may have to typecheck your component so it knows to expect message as a parameter! Please see the following post for some more context: https://fettblog.eu/typescript-react/components/. Here is a quick solution that might help!
import './App.css'
import * as React from "react";
type MyComponentProps = {
message: string
}
const MyComponent: React.FC = ({ message }: MyComponentProps) => {
return <h1>{message}</h1>
}

Related

Why can't I use this component with TypeScript?

I found a react-debounce-input library and I use it in my app without issues.
But since I moved to TypeScript, I'm getting an error when trying to use this library. Here's the minimal reproducible example:
import { FunctionComponent } from 'react';
import { DebounceInput } from 'react-debounce-input';
type Props = {};
export const Foo: FunctionComponent<Props> = () => {
return (
<form>
<DebounceInput />
</form>
);
};
The error I'm getting is:
TS2786: 'DebounceInput' cannot be used as a JSX component.
Its instance type 'DebounceInput<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>' is not a valid JSX element.
Type 'DebounceInput<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>' is missing the following properties from type 'ElementClass': render, context, setState, forceUpdate, and 3 more.
Am I missing something? According to the docs, it should work. I am using the newest version.
No problem with typescript:
import { FunctionComponent } from "react";
import { DebounceInput } from "react-debounce-input";
import { useState } from "react";
type Props = {};
export const Foo: FunctionComponent<Props> = () => {
const [state, setState] = useState("");
return (
<form>
<div>input: {state}</div>
<DebounceInput
minLength={5}
debounceTimeout={500}
onChange={(e) => setState(e.target.value)}
/>
</form>
);
};
Sandbox try it out
Side note on the type of react function, it can be written as:
const Foo: React.FC<Props> = () => { ... }
This way you don't have to do import { FunctionComponent } from "react";

Nextjs, react and TypeScript: prop type missing on FC using getInitialProps when used

I have a very basic React and Nextjs project built in TypeScript. I'm currently building this project from scratch to understand Nextjs better, I'm already quite proficient with TypeScript and React.
I have a simple Clock component built like below, and as per the nextjs documentation.
import { NextPage } from 'next';
import React, { useEffect } from 'react';
type Props = {
isoTime: string
}
const Clock: NextPage<Props> = ({ isoTime }: Props) => {
return <p>{isoTime}</p>;
}
Clock.getInitialProps = async () => {
return {
isoTime: new Date().toISOString()
};
};
export default Clock;
No problems here, however when I try and use this component elsewhere, for example in my app component...
import React from 'react';
import Clock from './clock/Clock';
function App() {
return (
<div className="App">
<Clock />
</div>
);
}
export default App;
I get the TypeScript error Property 'isoTime' is missing in type '{}' but required in type 'Props'. If I add a {/*#ts-ignore*/} above the error it compiles and works as expected, however I shouldn't have to remove typesafety just to get this to compile. How can I get TypeScript to pick up the props coming from getInitialProps?
According to nextJS documentation the put it as a optional props
interface Props {
userAgent?: string;
}
const Page: NextPage<Props> = ({ userAgent }) => (
<main>Your user agent: {userAgent}</main>
)
Page.getInitialProps = async ({ req }) => {
const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
return { userAgent }
}
export default Page
From you code it will be like this
type Props = {
isoTime?: string
}

Type '{}' is missing the following properties from type 'RouteComponentProps<{},,>'

So I'm quite new to React, and especially new to Typescript. I'm trying my best to wrap my head around it all so bare with me!
index.tsx
Router.tsx (all of the different routes)
LandingFrame.tsx (page layout)
import React from 'react';
import LandingMain from './LandingMain'
const LandingFrame = () => {
return (
<LandingMain/>
);
}
export default LandingFrame;
LandingMain.tsx (main)
import React, { forwardRef } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { useQuery } from '#apollo/react-hooks';
import gql from 'graphql-tag';
const YES = gql`
query yes {
yes {
id
data
data {
data
data
}
}
}
`;
const LandingMain = ({ history }: RouteComponentProps<{}>) => {
const { loading, error, data } = useQuery(YES);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>landing-page.js</h1>
{data.yes
? <p>Welcome back, {data.yes.data}</p>
: <p>Welcome back, Anon</p>
}
</div>
);
};
export default LandingMain;
(on a 2nd note) I'm hoping that by splitting the landing page, the frame would load first, following the graphql query in the main component. That way when the page loads it doesn't only return <p>Loading...</p> on a blank page before loading the rest.
TypeScript error in LandingFrame.tsx(22,14):
Type '{}' is missing the following properties from type 'RouteComponentProps<{}, StaticContext, PoorMansUnknown>': history, location, match TS2739
At this point I'm just trying to split up as much code as I can. But while doing so I noticed that TS won't let me import a component as easily as React would. From what I've read, I need to pass props somehow?
return (
<LandingMain/>
);
LandingMain expects to recieve routeComponentProps, but you are rendering it without said props. You need to add the props expected by the component.
It's my understanding that landing frame is also receiving RouteComponentProps, so this should work
const LandingFrame = (props: RouteComponentProps<{}>) => {
return (
<LandingMain {...props} />
);
}

How to make a functional Component in react and use destructive assignment? (I wrote some code but not working)

How do i make this into destructive assignment?
because it keeps giving me an error of
Binding element 'onClickBackDrop' implicitly has an 'any' type.ts(7031)
I am not sure what I am doing wrong
import React from "react";
import "../assets/stylesheets/BackDrop.css";
export default function BackDrop(props: any) {
const {onClickBackDrop()} = props;
return <div className="cs-backdrop" onClick={props.onClickBackDrop()} />;
}
import React, { FC } from 'react'
interface BackDropProps {
onClickBackDrop: Function
}
const BackDrop: FC<BackDropProps> = (props) => {
const { onClickBackDrop } = props;
return (
<div className="cs-backdrop" onClick={()=>onClickBackDrop()} />
)
}
export default BackDrop;
I was told to write the code like this
You don't need to run your function everywhere it used. also you can use destructive assignment in function component parameter.
import React from "react";
import "../assets/stylesheets/BackDrop.css";
export default function BackDrop({ onClickBackDrop }) {
return <div className="cs-backdrop" onClick={onClickBackDrop} />;
}
Declare (props: {onClickBackDrop: () => void}) or ({onClickBackDrop}:{onClickBackDrop: () => void}). You can omit type annotation but is bad in typescript.
and you probably want to use
<div ... onClick={onClickBackDrop} />
or
<div ... onClick={() => onClickBackDrop()} />
Please ignore my correction if onClickBackDrop indeed returns another function.
You can do it this way:
import React from "react";
export default function BackDrop({ onClickBackDrop }) {
return <div className="cs-backdrop" onClick={onClickBackDrop()} />;
}

Attempted import error: does not contain a default export

I'm defining react component to connect with redux . I have the app and list components
App.js
import React, { Component } from 'react';
//import Login from './components/Login';
import List from './components/List';
import './App.css';
class App extends Component {
render() {
return ( <List />); } }
export default App;
List.js
import React from 'react';
import { connect } from 'react-redux';
const mapStateToProps= state =>{
return { articles :state.articles};
}
const connectedList = ({ articles }) =>(
{articles.map(e=>( //////**1) here I get red under the dot(.) ie., error**
<li key={e.id}>{e.title}</li>
))}
);
const List= connect(mapStateToProps)(connectedList);
export default List;
why do 1) here I get red under the dot(.) ie., error
I have exported List but I'm thrown this error
Attempted import error: './components/List' does not contain a default export (imported as 'List').
Actually I'm newbie to redux so Please explain lemme know where i'm going wrong?
Remove curly brace:
const connectedList = ({ articles }) =>(
articles.map(e=>( // implicit return
<li key={e.id}>{e.title}</li>
)
));
Or, using curly brace:
const connectedList = ({ articles }) => { // no parentheses
return articles.map(e=>( // explicitly use return
<li key={e.id}>{e.title}</li>
)
});
Using curly brace in parentheses indicates that you're returning an object. But articles.map... is obviously not an object rather looping through an object.

Resources