Set up React with Typescript setup(ok)

https://www.educative.io/blog/react-and-typescript

npx create-react-app my-app --template typescript

# or

yarn create react-app my-app --template typescript

Link: https://blog.bitsrc.io/react-typescript-cheetsheet-2b6fa2cecfe2

Ví dụ 1:

C:\Users\Administrator\Desktop\hello-tsx\src\index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<React.StrictMode><App /></React.StrictMode>,document.getElementById('root'));
serviceWorker.unregister();

C:\Users\Administrator\Desktop\hello-tsx\src\App.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
import {ExtendedSelectableButton, SelectableButtonTypes} from './components/ExtendedSelectableButton/ExtendedSelectableButton'
const App = () => {
  return (
    <div className="App">
      <header className="App-header">
        <ExtendedSelectableButton type={SelectableButtonTypes.Important} text="Select me!!" action={ (selected) => {
          console.log(selected) 
        }} />       
      </header>
    </div>
  );
}
export default App;

C:\Users\Administrator\Desktop\hello-tsx\src\components\ExtendedSelectableButton\ExtendedSelectableButton.tsx

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
/** A set of groupped constants */
enum SelectableButtonTypes {
    Important = "important",
    Optional = "optional",
    Irrelevant = "irrelevant"
}
interface IButtonProps {
    text: string,
    /** The type of button, pulled from the Enum SelectableButtonTypes */
    type: SelectableButtonTypes,
    action: (selected: boolean) => void
}
const ExtendedSelectableButton = ({text, type, action}: IButtonProps) => {
    let [selected, setSelected]  = useState(false);
    return (
    	<button className={"extendedSelectableButton " + type + (selected? " selected" : "")} 
    	onClick={ 
    		_ => {
	        setSelected(!selected)
	        action(selected)
    		}
    	}>
    		{text}
    	</button>
    )
}
/** Exporting the component AND the Enum */
export { ExtendedSelectableButton, SelectableButtonTypes}

Last updated

Was this helpful?