Posts react typescript example
Post
Cancel

react typescript example

react typescript example

create react

1
npx create-react-app --template typescript react-typescript-example

App.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import React, { FC } from "react";

interface AppProps {
  sendSearchQuery(args: { search: string }): void;
}

//function App(){
//  function App({sendSearchQuery})
// const App=({sendSearchQuery}) => {
//  const App: React.FunctionComponent<AppProps> = ({sendSearchQuery} ) => {
const App: FC<AppProps> = ({
  sendSearchQuery = (args: { search: string }) => args,
}) => {
  const [searchValue, setSearchValue] = React.useState<string>();

  const onSearchInput = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchValue(event.target.value);
  };

  const search = () => {
    sendSearchQuery({ search: searchValue || "" });
  };

  return (
    <div>
      <input
        value={searchValue}
        onChange={onSearchInput}
        name="search"
        type="text"
      />
      <button onClick={search}>search</button>
    </div>
  );
};

export default App;

index.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const apiRequest = (args: { search: string }): void => {
  console.log(args);
};
ReactDOM.render(
  <React.StrictMode>
    <App sendSearchQuery={(args: { search: string }) => apiRequest(args)} />
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

run

Link

https://www.youtube.com/watch?v=e5c_RfYqIhU&list=PLIvCYh5AD3HxZ0J4bEEiSDJWeeN9mNNLL&index=1

This post is licensed under CC BY 4.0 by the author.