Maaz Azeem
Maaz Azeem

Reputation: 49

Enable button based on map value React

I have a component that renders a list of books into bootstrap cards with a checkout button. I have a state for the checkout button called disabled.

I want to enable the button only if the books.quantity>0. How can I successfully change the state of this button?

    constructor(props) {
    super(props)

    this.state = {
        books: [],
        message: null,
        disabled: true
    }

}

    render() {

    return (
        <Container fluid>
            <Row>
                {
                    this.state.books.map(
                        books =>
                            <Col key={books.id} sm="2">
                                <Card style={{ width: '18rem' }}>
                                    <Card.Img variant="top" src="http://res.freestockphotos.biz/pictures/14/14301-illustration-of-a-book-pv.png" />
                                    <Card.Body>
                                        <Card.Title>{books.title}</Card.Title>
                                        <Card.Subtitle> {books.author.firstName + " " + books.author.lastName} </Card.Subtitle>
                                        <Card.Subtitle > {books.quantity} </Card.Subtitle>
                                        <Button disabled={this.state.disabled}  variant="primary" >Checkout</Button>                                        
                                    </Card.Body>
                                </Card>
                            </Col>
                    )
                }
            </Row>
        </Container>
    );
}

Upvotes: 0

Views: 76

Answers (1)

norbitrial
norbitrial

Reputation: 15166

You can add to the disabled attribute the following:

<Button disabled={books.quantity > 0} variant="primary">Checkout</Button> 

This will check the value of books.quantity > 0 and enable the button if the statement is true.

Upvotes: 1

Related Questions