mercredi 14 juillet 2021

ReactJs: How to pass data from one component to another?

If two or more cards from a component are selected how to pass data to a button component?

I have a landing page that holds two components; Template list and a button.

<TemplateList templates={templates} />

                <MenuButton style={actionButton} onClick={onOnboardingComplete}>
                    Select at least 2 options
                </MenuButton>

The TemplateList brings in an array of information for my Template and creates Template Cards with it. I am then able to select my cards and unselect them.

My Button when pressed just takes me to the next step of the onboarding.

I would like to know how I should approach linking these two components. My button now is gray and would like this to happen:

1. Button is gray and user cant go on to next step, until selecting two or more cards.

2. When two or more cards are selected, button turn blue and they are able to press the button to continue.

This is my Template List:

export type Template = {
    title: string;
    description: string;
    imgURL: string;
    id?: number;
};

type Props = {
    templates: Template[];
};

const TemplateList = ({ templates }: Props) => {
    return (
        <div className={styles.scrollContainer}>
            {templates.map((item) => (
                <TemplateCard
                    title={item.title}
                    description={item.description}
                    img={item.imgURL}
                    classNameToAdd={styles.cardContainer}
                    key={item.id}
                />
            ))}
        </div>
    );
};

export default TemplateList;

And this my Template Card:



type Props = {
    title: string;
    description: string;
    img: string;
    classNameToAdd?: string;
    classNameOnSelected?: string;
};

const TemplateCard = ({ title, description, img, classNameToAdd, classNameOnSelected }: Props) => {
    const { aspectRatio, vmin } = useWindowResponsiveValues();
    let className = `${styles.card} ${classNameToAdd}`;

    const [selected, setSelected] = useState(false);

    const handleClick = () => {
        setSelected(!selected);
    };

    if (selected) {
        className += `${styles.card} ${classNameToAdd} ${classNameOnSelected}`;
    }
    return (
        <div style={card} className={className} onClick={handleClick}>
            <img style={imageSize} src={img}></img>
            <div style={cardTitle}>
                {title}
                {selected ? <BlueCheckIcon style={blueCheck} className={styles.blueCheck} /> : null}
            </div>
            <div style={descriptionCard}>{description}</div>
        </div>
    );
};

TemplateCard.defaultProps = {
    classNameOnSelected: styles.selected,
};

export default TemplateCard;

This is how it looks like now. enter image description here

Aucun commentaire:

Enregistrer un commentaire