Dorokhov.codes

05. Creating components

React component is a function or a class that returns JSX elements.

const Header = () => {
    return <h2>Hello, world!</h2>;
};
class Header extends React.Component {
    render() {
        return <h2>Hello, world!</h2>;
    }
};

Now we can use this component in other JSX elements:

<Header />

It’s a good practice to place every component in a separate file. Here’s an example of such a file:

// App.js
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
      </header>
    </div>
  );
}

export default App;

Inline styles

We can use an object with CSS properties and pass it to the style:

const styles = {
    width: "300px"
};

const el = <div style={styles}></div>;

Properties

Example:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;

Destructuring:

const Header = ({name, age}) => {
    return <h2>Hello, {name}!</h2>;
};

React.Component class has a constructor in which it stores props parameter into the props property. So we can use the props property in methods.

class Header extends React.Component {
    render() {
        const {name, age} = this.props;
        return <h2>Hello, world!</h2>;
    }
};

Key for list items

List items should have a unique key attribute. These attributes should be unique only along their neighbours (not globally). Example:

const items = data.map(item => {
    const {id, ...props} = item;
    return <EmployeesListItem key={id} {...props} />
});