Coder Social home page Coder Social logo

pro-react-16's Introduction

Apress Source Code

This repository accompanies Pro React 16 by Adam Freeman (Apress, 2019).

Cover image

Download the files as a zip using the green button, or clone the repository to your machine using Git.

Releases

Release v1.0 corresponds to the code in the published book, without corrections or updates.

Contributions

See the file Contributing.md for more information on how you can contribute to this repository.

pro-react-16's People

Contributors

markp88 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pro-react-16's Issues

[SOLVED] issue in listing 20-9 customReducerEnhancer

I've found issue with code in listing and i give it a try by changing the initialState = null from being null to initialState = initialData and it works correctly

also another change works by just changing return initialState to return initialData in this snippet:

return (storeData, action) => {
 if (action.type === STORE_RESET && initialData != null) {
 return intialState; //change this to initialData
 } else {
...

and i want to say thank you for this amazing book, i've learned a lot

Listing 11.6 - Counter state changes from second click on page

Hello,
There seems to be an issue. After page loads, and one clicks either Promote or Reverse button, the first click (on any button) does not increment the counter. After the first click, the counter works for all buttons.

My code is as follows:

import React, {Component} from 'react';
    export class SimpleButton extends Component{
    constructor(props){
        super(props);
        this.state = {
            counter: 0,
            hasButtonBeenClicked: false
        }
    }
    render(){
        return (
            <button onClick={this.handleClick} className={this.props.className} 
                    disabled={this.props.disabled==="true" || this.props.disabled === true}  >
                {this.props.text} {this.state.counter} {this.state.hasButtonBeenClicked && <div>Button Clicked!</div>}
            </button>
        )
    }

    handleClick = () => {
        this.setState({
            counter: this.state.counter + 1,
            hasButtonBeenClicked: true
        });
        this.props.callback();
    }       
}




import React from 'react';
import {SimpleButton} from './SimpleButton';

export function Summary(props){
    return (
        <React.Fragment>
            <td> {props.index + 1} </td>           
            <td> { props.name }  </td>  
            <td> {props.name.length } </td> 
            <td>
                <SimpleButton className="btn btn-warning btn-sm m-1" callback={ props.reverseCallback }  text={`Reverse (${props.name})`}   />
                <SimpleButton className="btn btn-info btn-sm m-1" callback={ () => props.promoteCallback(props.name) } text={`Promote (${props.name})`}  />
            </td>           
        </React.Fragment>
                
    );
}



import logo from './logo.svg';
import './App.css';
import React  from 'react';
import { Summary } from './Summary';
import ReactDOM from "react-dom";

let names=["Bob", "Alice", "Dora"];

function reverseNames(){
  names.reverse();
  ReactDOM.render(<App />, document.getElementById('root'));
}


function promoteName(name){
  names = [name, ...names.filter(val => val !== name)];
  ReactDOM.render(<App />, document.getElementById('root'));
}

function App() {
  return ( <table className="table table-sm table-striped">
      <thead>
        <tr><th>#</th><th>Name</th><th>Letters</th></tr>
      </thead>
      <tbody>
        { 
             names.map( (name,index) => 
             <tr key={name}><Summary index={index} name={name} 
              reverseCallback={reverseNames} 
              promoteCallback={promoteName} /> </tr>) 
        }
      </tbody>
    </table>
  );
}
export default App;


confusion about setState on page 411 of the book

in the api doc: https://reactjs.org/docs/react-component.html#setstate

state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props. For instance, suppose we wanted to increment a value in state by props.step:
this.setState((state, props) => {
return {counter: state.counter + props.step};
});

in the book "pro-react-16" page 411:

toggleProMode = () => {
this.setState(state => state.proContextData.proMode
= !state.proContextData.proMode);
}

according to the api doc, page 411 is not workable, because in the function

state => state.proContextData.proMode = !state.proContextData.proMode

there is no explicit return, so the return value is the result of 'state.proContextData.proMode = !state.proContextData.proMode', which is !state.proContextData.proMode, let's assume it's 'true', obviously 'true' is not the state object
but I tested the code, it works, could you please explain why? thanks!

Typos

Hello, I am not sure that it is the place for such reports, but anyway.


Page 162:

Listing 6-34. Simplifying the Code in the ShopConnector.js File in the src/connectors Folder

should be

Listing 6-34. Simplifying the Code in the ShopConnector.js File in the src/shop Folder

Page 604, Listing 21-10:

import React, { Component } from "react";
import { BrowserRouter as Router, Link, Route, Switch } from "react-router-dom";
import { ProductDisplay } from "./ProductDisplay";
import { SupplierDisplay } from "./SupplierDisplay";

In second like Switch should be bold as well as line 3 and 4


Page 604:

Each Route component assesses its path prop independently; this can be useful but isn’t ideal if you want
just one component to be display based n the current URL. For these situations, the Redux-Router package
provides the Switch component, which acts as a wrapper around multiple Route components, queries them
in order, and displays the content rendered by the first one to match the current URL. Listing 21-10 shows
the use of the Switch component.

Redux-Router is incorrect, should be react-router-dom

Error Listing 1-17

onChange={() => this.props.callback(this.props.item)} throws an error that reads _this.props.callback is not a function.

Chapter 8 - log in doesn't work

I opened code from Chapter 8, wrote npm install, then npm start, went to http://localhost:3000/admin. In the form - admin was typed in the login input, and I typed secret as password, then clicked Login button. Then red banner with Request failed with status code 404 popped up. I didn't change anything at code.

Chapter 12 Working with React

Hi

Listing 12-22Identifying Capture Phase Events in the ThemeButton.js File in the src Folder

src\ThemeButton.js
Line 9:17: 'capturePhase' is not defined no-undef

Chapter 14 input checkbox after Context changes

Hi,

I'm having trouble with the code between 412-416.

After making the changes on page 416 and when I started using Context, I noticed that the input checkbox doesn't work anymore to disable/enable the sort button and the button doesn't change colors either.
I noticed that the input checkbox's onChange property is being set to contextData.toggleProMode which in ProModeContext.js is set to an empty function. I think this might be the code change that is causing the errors above, because before it was set to the toggleProMode function in App.js that actually worked. Can someone help here?

Need to update this line using

Hi, I think this

should be
let selection = newStore.cart.find(item => item.product.id === action.payload.product.id);
where action.payload.id becomes action.payload.product.id
I am new to javascript and react so I apologize if this is incorrect but this is what I came up with to get the 'Remove' button in the cart to work.

Bug Listing 5-31

Changing the quantity of product, the event produces string which has the concatenation operator precedence over addition, it works to explicitly convert string to numbers in Listing 5-31 as follows
...
handleChange = (product, event) => {
this.props.updateQuantity(product, Number(event.target.value));
}
...

Chapter 5 - CartReducer

Hi Adam,

in Chapter 5 inside the CartReducer you have this:

        let existing = newStore.cart.find(item => item.product.id === p.id);
        if (existing) {
            existing.quantity += q;
        } else {
            newStore.cart = [...newStore.cart, action.payload];
        }

The problem is: If the item already exists in the cart, you change the quantity of the existing item. But: This changes storeData, because existing is inside storeData AND inside newStore. So this makes the function unpure, i.e. it is not what you want as a Reducer.

Chapter7 - Administration

Hi!
After finishing code to 7-15 and starting the app, the browser shows this error:

TypeError: orders is undefined
props
src/admin/OrdersConnector.js:16

13 | {
14 | options: (props) => ({variables: vars}),
15 | props: ({data: {loading, orders, refetch}}) => ({

16 | totalSize: loading ? 0 : orders.totalSize,
| ^ 17 | orders: loading ? [] : orders.orders,
18 | currentPage: vars.page,
19 | pageCount: loading ? 0 : Math.ceil(orders.totalSize / vars.pageSize),
...

I'm stuck in this part :( and need some help here.

Chapter 8 Auth and Deployment

Hello :) !
I started testing app after picture 8.3.
(Firefox and Chrome)

After making purchases in the store, logging in to the administration panel, select the last page to find the orders placed, the following appears:

Unhandled Rejection (Error): GraphQL error: Cannot return null for non-nullable field order.name.

Best Regards I am waiting for the info;)

Chapter 5: TypeError: this.props.addToCart is not a function

I got this error in ProductList.js:
<button className="btn btn-success btn-sm float-right" onClick={ () => this.props.addToCart(p) }>

=> TypeError: this.props.addToCart is not a function.

I've found some suggestions on SOF that we must take care of importing component but nothing works. What should I do?

What's the purpose of "value={ this.state[top] }" in Listing 15.12

New to React..Going through the examples... Please help if you can

<label>Ice Cream Toppings</label>
{ this.toppings.map(top =>
<div className="form-check" key={ top }>
<input className="form-check-input"
type="checkbox" name={ top }
value={ this.state[top] }   <============================================
checked={ this.state.toppings.indexOf(top) > -1 }
onChange={ this.updateFormValueCheck } />
<label className="form-check-label">{ top }</label>
</div>
)}

State is declared as
this.state = {
name: "",
flavor: "Vanilla",
toppings: ["Strawberries"]
}

toppings has array for all selected values,, what's the purpose of this.state[top]?

ch.13 page 370

The function passed to useState can return a cleanup function [...]

should it be

The function passed to useEffect can return a cleanup function [...]

?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.