JS.React. Components in functional style

install react

npx create-react-app my-app
cd my-app
npm start

Source code

What is interesting ?

Example of component

import React from "react";
import cc from 'classcat';
import styles from './House.module.css';

export const House = ({
                          src,
                          alt,
                          title,
                          price,
                          location,
                          isSold
                      }) => {

    const styleTitle = cc({
        [styles.title]: true,
        [styles.isSold]: isSold
    });

    return (
        <div className={styles.house}>
            <img className={styles.image} src={src} alt = {alt}/>
            <p className={styleTitle}>{title}</p>
            <p className={styles.price}>{price}</p>
            <p className={styles.location}>{location}</p>
        </div>
    )
}

Css module (work from the box in react), we can use style var or any other we define

...
import styles from './House.module.css'; // << add word module to css file for webpack
...

// below you can call like this
<div className={styles.house}>
            <img className={styles.image} src={src} alt = {alt}/>
            <p className={styleTitle}>{title}</p>
            <p className={styles.price}>{price}</p>
            <p className={styles.location}>{location}</p>
        </div>

class cat lib for conditional modifications of styles

import cc from 'classcat'; // import with npm first
...
    const styleTitle = cc({
        [styles.title]: true,
        [styles.isSold]: isSold
    });

adding event handlers and use state

import {useState} from 'react';
import React from "react";
import styles from './NavigationBar.module.css';

export const NavigationBar = () => {

    const leftButtonValue = '<';
    const rightButtonValue = '>';

    const [myName, setMyName] = useState(0);

    const handleRightClick = (e) => {
        setMyName(myName + 1);
        console.log(myName);
    }

    return (
        <div className={styles.navigation}>
            <progress className={styles.progress} value="0" max="100"></progress>

            <button className={styles.buttons__left} >
                {leftButtonValue}
            </button>
            <button className={styles.buttons__right} onClick={handleRightClick} >
                {rightButtonValue}
            </button>
        </div>
    );
}
This entry was posted in Без рубрики. Bookmark the permalink.