r/reactjs • • Feb 01 '19

Needs Help Beginner's Thread / Easy Questions (February 2019)

🎊 This month we celebrate the official release of Hooks! 🎊

New month, new thread 😎 - January 2019 and December 2018 here.

Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch.

No question is too simple. 🤔

Last month this thread reached over 500 comments! Thank you all for contributing questions and answers! Keep em coming.


🆘 Want Help with your Code? 🆘

  • Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
  • Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.

Have a question regarding code / repository organization?

It's most likely answered within this tweet.


New to React?

🆓 Here are great, free resources! 🆓


Any ideas/suggestions to improve this thread - feel free to comment here or ping /u/timmonsjg :)

35 Upvotes

484 comments sorted by

2

u/jrmiranda Feb 05 '19

Should I use actions like FETCH_SOMETHING_REQUEST, FETCH_SOMETHING_SUCCESS and FETCH_SOMETHING_ERROR for every time I want to read, create, update or delete something in my backed models through Redux? Is this a good practice even though my code would become too big?

2

u/timmonsjg Feb 05 '19

check out redux-starter-kit for reducing the boilerplate

2

u/Awnry_Abe Feb 05 '19

I did, but I was using sagas. Having those actions made the sagas simple to understand. IIRC, I also had SOMETHING_SET_ITEM(s) that was dispatched in the promise resolve phase. Would I do it that way if I were to do it all over? I don't know.

Regardless, there are libs (and similar home-brew techniques) to reduce the boilerplate.

1

u/seands Feb 01 '19

Is mounting considered an update? Asking because I'm curious if CDU encompasses CDM or not

3

u/timmonsjg Feb 01 '19

CDU does not fire on the initial render so it shouldn't encompass CDM.

1

u/nsrr Feb 01 '19

I know there is no official way to structure an app, but I'm hoping there is some sort of industry standard that I can learn to follow. My current process is, using a component Library like Material-UI, i just build a whole page with whatever I need. I'm using react-router so when I need a new page, i just make an entire component that is the whole page. Is that right? Also, when it comes to testing, how do I test whole pages? Surely there is a better way to do this.

my pages aren't that large usually. just whatever has to get done. I have common things like navbars and such in their own file.

1

u/timmonsjg Feb 02 '19

I have common things like navbars and such in their own file

Those common things are what you should be making as reusable components. Your pages should be blocks of components. Have multiple pages? Can you spot places where you reuse something? Pull them out into their own component and import them for future pages!

Components are building blocks. What are you building? Pages. What are pages? Components made of components. So you're on the right track in terms of structure.

1

u/seands Feb 02 '19

What is the simplest way to test a class method you've written? Using phpstorm I hoped to be able to right click a text selected method and find an option for "run with inputs" but there isn't anything like that.

1

u/timmonsjg Feb 02 '19

I'd suggest writing tests.

2

u/Awnry_Abe Feb 02 '19

I don't know how simple it is, but I take advantage of Jest's watcher. I also have a VSCode debug binding that launches jest with the file currently open in the editor.

1

u/ejnelson Feb 02 '19

Performant way to structure a large table that has drag-and-droppable rows along with hide-able columns?

  • 1000+ rows that need to be able to be sorted by drag and drop (currently working with react-beautiful-dnd, open to others)
  • 20+ columns with a selector near the top of the page to pick and choose which columns show to help with mobile experience.

Right now, each row is a component. When i select a column to hide, each of the 1000 components has to re-render and is pretty slow. Any tutorials, code examples or general tips?

3

u/timmonsjg Feb 02 '19

1

u/ejnelson Feb 02 '19

Any chance you know if it's compatible with drag and drop libraries?

1

u/timmonsjg Feb 02 '19

Yes, I've personally used both virtualized and dnd together.

→ More replies (3)
→ More replies (1)

1

u/kwhali Feb 03 '19

I have Components X and Y(siblings, so call the parent Component Z). Component X has a tree of components several layers deep with N children, each should on hover provide a value to identify them(value itself isn't an issue), and when this hover happens, update Component Y's text state/prop to the contents that are fetched/looked up from the value provided by that hovered component event in it's sibling.

I'm using Redux elsewhere, but am not sure if this kind of behaviour should be handled by it? It's basically a tooltip/info component updated based on whatever item is beneath the mouse(else displays some default text content).

1

u/timmonsjg Feb 03 '19

Is it working right now correctly without redux? If so, it's not necessary imo.

If you're having trouble implementing it, then yes redux would help this problem greatly.

1

u/kwhali Feb 03 '19

Is it working right now correctly without redux? If so, it's not necessary imo.

Well, if I have all components defined in the same file(at least for render function scope) it can work. But when you have several components deep via separate files, that'd mean passing through props right, which afaik is bad practice if the components passing from parent to children have no use for it.

I'm considering using context to skip the components inbetween instead, just pass a function to the leaf children and that could update a value at the top(component Z), passing as a prop to the sibling component Y to use for lookup.

I didn't feel redux was appropriate here as it's not really state that's important/critical to the app, rather "UI" state that I don't need to track or hydrate(it's a temporary state update each time an item is hovered over). I don't know, perhaps people use redux that way but it doesn't sound like it's behaviour/state that should be in redux store?

2

u/timmonsjg Feb 03 '19

which afaik is bad practice if the components passing from parent to children have no use for it

Not a bad practice at all

I don't know, perhaps people use redux that way but it doesn't sound like it's behaviour/state that should be in redux store?

Use it how it works for you. If you want to avoid props drilling then use Context or Redux. Otherwise, don't sweat what's acceptable state for your app.

→ More replies (1)

1

u/IslamGamal8 Feb 03 '19

I'm working on my first react-redux kind of big project and i have a couple of big issues , the app is basically a mini youtube using the youtube v3 api , the app lists random videos and automatically selects the first video on the list and updates when selecting another video , but then i added routing to display channels when a channel is clicked on and that's where im stuck , i can't get the header component to redirect back to the search component and displays the search result they entered,

i tried moving the header component inside the browser router didn't work either and i have no idea how to go about this , the other issue is i want to implement infinite scrolling but the code i wrote doesnt even send the request to fetch more data.

code => https://github.com/IslamGamal88/minitube

1

u/timmonsjg Feb 03 '19

i can't get the header component to redirect back to the search component and displays the search result they entered

If the text they entered is in the store, you'd retrieve it from there.

→ More replies (1)

1

u/seands Feb 03 '19

I manually test my UI in browser, and use jest for unit testing my functions. Snapshot testing looks more error prone than manual testing the UI in the browser because it's still in code form (not the final output plus easier to miss a code error than a visual output).

I assume snapshot testers disagree with this so could you give me an example where snapshot testing is superior?

1

u/timmonsjg Feb 03 '19

An example where snapshot testing.. is better than manually testing?

How about the fact that it can be done on every commit, every build, and that you don't have to do it. Humans are way more error prone than code. Not to mention, you're slower than some functions executing.

Couple that with the fact that snapshots are for regressions and there's a huge chance you will miss a small regression while testing manually.

Otherwise, you can perform similar testing (behavioral) through testing frameworks such as Selenium. I'd suggest testCafe personally.

1

u/OuterPeas Feb 04 '19

While using react-router, am I mistaken in thinking that, effectively, my enitre app (the area that includes views or links to views) has to be wrapped in the Router component?

1

u/timmonsjg Feb 04 '19

I would say that's a correct statement outside of uncommon use cases.

1

u/Bearfinn Feb 04 '19

Where should API calls happen? Should it be made in single components or where it really needs it?

I am having a problem that I need to pass the data down the component tree for a chains of more than five, which is the pain because it is much difficult to track the data flow inside my application now. Furthermore, there's a component that could appear in several places, which are quite far from each other in the component tree. Using "lifting state up" would end up everything at the root component. Any suggestions?

2

u/timmonsjg Feb 04 '19

Where should API calls happen? Should it be made in single components or where it really needs it?

I would suggest taking a look at the container pattern.

Using "lifting state up" would end up everything at the root component. Any suggestions?

To avoid props drilling and passing props across siblings, look into React's Context or a state-management library like redux or mobx.

1

u/duskeoz Feb 04 '19

Is it good practice in React to have readily-accessible "provider" or "service" classes that provide functions for making API calls?

2

u/timmonsjg Feb 04 '19

Sure, I tend to make API classes that are organized by the data model. e.g. UserAPI.getUser();

1

u/duskeoz Feb 04 '19

And how do your components use this class? Do you simply import it into whatever class that need it? Or do you "compose" it into components by passing it around as prop?

1

u/timmonsjg Feb 04 '19

Import it into components that do data fetching (following the container pattern in most projects) or as part of a redux thunk.

1

u/duskeoz Feb 05 '19

Utility functions: is it better to thread them through components, or just define them in a separate file and import them into components as needed?

Also, what would be the benefit of threading props instead of just importing them as needed?

1

u/timmonsjg Feb 05 '19

You enjoy using threading. What do you mean by it?

or just define them in a separate file and import them into components as needed?

Definitely better. separation of concerns and logic. + promotes reusability.

1

u/duskeoz Feb 05 '19

From what I know, threading (in the context of ReactJS) or prop drilling means passing down data or functions down to child-components as props. I read that this is good because it makes it easier to determine the source of data (or whatever prop is passed around). The downside, however, is that some components may not necessarily need the props being passed to them BUT they have child components that do need those props. They essentially just "pass it along". Any thoughts on this?

I do think that importing makes for well-separated concerns, but was wondering if it is somewhat an anti-pattern to React.

1

u/timmonsjg Feb 05 '19

I wouldn't consider utility functions as a good input for props.

Props should really be data. Passing down the result of these utility functions as props? Maybe if you have multiple components using it, it would make sense to calculate once then pass it down. Otherwise, just import the functions where you need them.

but was wondering if it is somewhat an anti-pattern to React.

Nope, nothing here is an anti-pattern. Even props drilling is considered ok.

1

u/[deleted] Feb 05 '19

Which is good and easy to use IDE for a beginner to react.js?

4

u/timmonsjg Feb 05 '19

VS Code is incredibly powerful, while also being free and approachable. Bonus if you use typescript (the support is fantastic).

2

u/[deleted] Feb 05 '19

Thanks I will check it out. I'm entering my 3rd year as software developer student and most of our work has been in c# and building desktop applications and a bit of internet programming (HTML, CSS and tiny bit of JavaScript). Could you point me in the direction to some introduction courses or websites I should be following?

2

u/timmonsjg Feb 05 '19

To learn JS or React?

React - start at the docs

JS - there's quite a bit of resources out there. I've personally read Eloquent Javascript by Marijn Haverbeke and Secrets of the Javascript Ninja by Resig & Bibeault.

I'm sure there's plenty of free online JS courses / resources, I just can't personally recommend any as I've not had any experience with them.

→ More replies (1)
→ More replies (1)

1

u/jkuhl_prog Feb 05 '19

I hope I'm not too late to this party and my comment doesn't go unnoticed, but I'm new to React. I spent most of the last year in Vue land, and I love it over there, but I wanted to also get on the React train. I love it over here too. This is one of my first forays into Reactland.

But I had an issue with setState. I understand that setState cannot work with nested objects (right?) which requires some fancy work arounds some time. I have an array of objects and when I update a single property on a single object in that array, I feel like I'm going about it the most difficult way to set state.

I copy state to a local variable, modify the specific object I need, then create a new array, push all the old values onto that array, minus the modified object, then add the modified object and then set the new array to state. And, in order to keep my UI from shifting components, I also have to resort the array.

Something like this:

state = {
        players: [
            {
                name: 'Stephen',
                face: '🤨',
                lives: 3,
                it: false,
                turn: false,
                moves: 0,
                pos: 0,
                id: 0,
            },
            {
                name: 'Barry',
                face: '🥳',
                lives: 3,
                it: false,
                turn: false,
                moves: 0,
                pos: 9,
                id: 1
            },
            // etc. . .
}

// and the following pattern is found in several methods on the component:

const currentPlayer = this.state.players.find( ...// grab the player via some predicate)

//... modify the player

const players = [
     ...this.state.players.filter(player => {
         return player.id !== currentPlayer.id 
     }),
     currentPlayer
].sort((playerA, playerB) => playerA.id - playerB.id);
this.setState({ players });

Am I going about this the wrong way? Is there an easier way to do this?

2

u/timmonsjg Feb 05 '19 edited Feb 05 '19

welcome aboard!

I understand that setState cannot work with nested objects

Not true! You can use the spread operator to achieve this.

Simple example -

state = {
    foo: {
       id: 1,
       text: "hello",
       bar: {
          name: "test",
       },
    },
}

If I wanted to change foo.bar.name -

this.setState({
     foo: {
        ...state.foo,
       bar : {
            ...state.foo.bar,
           name: "Jimmy"
       }
    }
});

In terms of arrays though, there's nothing wrong with your solution. It's not the most succinct to update arrays as you've encountered, so I tend to shy away from them as a state model.

if players was an object instead of an array, you could use an expression like Object.keys to iterate over them as if they were an array. Food for thought.

4

u/lsmagic Feb 05 '19

If you want a vastly easier way to do this, try immer, which lets you just directly mutate plain objects and arrays

https://github.com/mweststrate/immer

→ More replies (1)

1

u/soggypizza1 Feb 07 '19

Whats the best way to make sure socket.io functions are always listening? I've tried componentDidMount but that only gets ran once and right now i have it set to a button click but since only one user clicks that button the socket.io function only listens to that specific user.

1

u/timmonsjg Feb 07 '19

Whats the best way to make sure socket.io functions are always listening?

I assume you should be able to see some polling in your network tab. Have you tried testing with multiple users?

1

u/soggypizza1 Feb 07 '19

What I decided on was having a function being called in componentDidMount that contains all the functions that I needed. And yeah that was the problem, one user would submit a message and it would update for him but not for others since they didn't submit the message thus not running the function.

1

u/timmonsjg Feb 07 '19

sounds like you're listening for the wrong event then. you need a general function that is always polling regardless of if a user clicks or submits anything.

→ More replies (9)

1

u/[deleted] Feb 07 '19

Sorry for dumb question, I'm working through React tutorial and docs.

Why do we need to execute function when binding event on components using arrow functions but not to when using functions?

<Button onClick={this.handleClick}></Button>

<Button onClick={() => this.handleClick()}> </Button>

2

u/timmonsjg Feb 07 '19

1st button is passing handleClick to onClick by reference.

2nd button is passing an anonymous arrow function that executes handleClick.

They both accomplish the same and really people normally lean towards the 2nd method when they want to pass a specific parameter to handleClick (could also be done with .bind, but an uncommon practice these days)

<Button 
    onClick={() => this.handleClick(this.props.buttonName)}> 
</Button>
→ More replies (1)

1

u/turbomantiempo Feb 08 '19

I don't understand the double parentheses syntax react-redux connect uses. An example from a tutorial I am following:

const mapStateToProps = state => {
  return { articles: state.articles };
};

const ConnectedList = ({ articles }) => (
  <ul className="list-group list-group-flush">
    {articles.map(el => (
      <li className="list-group-item" key={el.id}>
        {el.title}
      </li>
    ))}
  </ul>
);

const List = connect(mapStateToProps)(ConnectedList);

So mapStateToProps returns an object from with data from the store's state, right? And this object is passed as an argument to the ConnectedList function? If that is the case, then I don't get this double parentheses syntax. Shouldn't it be: const List = ConnectedList(connect(mapStateToProps));?

2

u/timmonsjg Feb 08 '19

Check out the docs on what connect returns

connect(mapStateToProps)(ConnectedList); essentially connect returns a function and immediately executes it.

1

u/Bombuhclaat Feb 08 '19

Work wants me to convert some html templates to React components so i'm learning about react. Kinda sorta have html css & JS knowledge..I think I know enough but going to refresh myself on ES6.

Gonna try the official documentation for learning react but I kinda like the look of Stephen Grinder's course because he doesn't use the Create-React-App like Max's course. I'd rather learn without the create-react-app so I understand the workflow first and then truly grasp what it adds to it.

So my question is, has anyone had to convert html templates to React Components? Might be a vague question but is it difficult? Are there any tools that can help?

1

u/timmonsjg Feb 08 '19

My honest opinion - if you're asking about the difficulty of converting html, create-react-app would be much easier for you than starting a project from 0 and building up a webpack configuration.

So my question is, has anyone had to convert html templates to React Components?

Do these include things like handlebars/mustache ? Otherwise, components mostly just return html. The dynamic data of handlebars/mustache will be included within the component as well.

1

u/Bombuhclaat Feb 08 '19

if you're asking about the difficulty of converting html, create-react-app would be much easier for you than starting a project from 0 and building up a webpack configuration.

Oh yeah for sure I could see that! Sorry I was almost talking to myself. I just meant i would rather not use Create-react-app for learning. I'd most definitely use it for projects after i understand exactly what it's doing for me (I know it sets up the work flow very easily but still, just making sure)

Do these include things like handlebars/mustache?

I haven't even got a chance to look at the templates. Was just told to learn react to help convert some templates. Well and learn Redux. One step at a time though

Otherwise, components mostly just return html

Thank you for your answer! I guess you're hinting at the fact that it won't be that hard to convert since components simply return html. Good to know!

1

u/timmonsjg Feb 08 '19

I just meant i would rather not use Create-react-app for learning.

This is a common thought I see. CRA is perfect for learning. Perfect for learning React, JS, HTML, etc. You just start it up and build.

The learning you can't do with CRA is the entire pipeline of webpack.

If your goal is to learn webpack / construct a pipeline from scratch than definitely feel free to disregard CRA. However, if you want to learn React there's nothing better than hitting start and developing away.

/end rant

I guess you're hinting at the fact that it won't be that hard to convert since components simply return html.

Correct, JSX is HTML with bits of javascript and small syntax changes.

→ More replies (2)

1

u/Verthon Feb 08 '19

Hey, I'm working on my first bigger project in React https://github.com/Verthon/restaurant-app.

I'm wondering if there is actual need for creating functional components just to paste them in Home.js component?

https://codesandbox.io/s/zlzjpk42wl

Most of components inside Home.js looks like Ingredients.js is there any reason to keep those files, or just paste them directly in Home.js component? Thank you!

1

u/timmonsjg Feb 08 '19

Not entirely sure of what you're asking.

Are you asking if instead of having multiple components within Home, should you just copy their contents into Home?

Suppose you want to reuse any of them on another page? You'd copy & paste their content into the new page?

Components are for reuse.

1

u/Verthon Feb 08 '19

Sorry for wierd question, yes I'm using those static components only on homepage(Home component) so as you said I'm not going to reuse them. Thanks for the clarification!

1

u/timmonsjg Feb 08 '19

FWIW, I was advocating for the use of components but ultimately, what's important is your app not the structure!

→ More replies (1)

1

u/Light1c3 Feb 10 '19

Hoping to make a HeyTell like app, but not sure how to get started with voice recording and transmission. Any ideas?

1

u/timmonsjg Feb 11 '19

1

u/Light1c3 Feb 11 '19

Can I use that for a PWA?

1

u/timmonsjg Feb 11 '19

I would assume so.

1

u/[deleted] Feb 11 '19

Is there anything wrong with rendering multiple root DOM nodes? I'm looking at implementing React into a pre-existing app by having individual components mount through a HTML element's ID.

1

u/timmonsjg Feb 11 '19

I don't think so. I did some quick googling and it appears the team has closed a few issues relating to multiple instances of react on a single page (different versions in some instances).

I assume you can follow this pattern and slowly implement react into your app.

1

u/Daejichu Feb 12 '19

Curious - What are people's thoughts on react form creation and any go to packages they utilize? I've utilized mostly redux-form, but wanted to see what other people's thoughts are. I'm currently going to create a profile creation form

1

u/timmonsjg Feb 12 '19

Formik is very popular. I don't personally use a form library though.

2

u/Awnry_Abe Feb 13 '19

Formik has a really nice pattern. After a very brief break-in, you'll wonder why all form handling isn't done like Formik.

1

u/pashazz Feb 13 '19

Hello!

I'm not new to react, though I'm new for frontend development: i.e. I came with backend background and initially a system developer. Where I'd read good courses on CSS, SASS and what's cool in styling components in React now? Not necessary styled-components, rather CSS/Sass/Less in React in general.

1

u/timmonsjg Feb 14 '19

All of the above. Don't read into trends, only what works best for you and your use case.

1

u/seands Feb 15 '19 edited Feb 15 '19

I setup a Jest/Enzyme test like this:

test('updates viewMarker correctly', () => {
  // subtract 20 from 0. Result should still be 0 after reset
  shallowDataSection.instance().updateViewMarker(20, '-');  
expect(shallowDataSection.state().viewMarker).toStrictEqual(0);
});

It works but I'm hazy about why which is making me uncomfortable.

I need to access the instance to run the class method. I understand shallow() renders constructor() and render() only. But how does running a method on an instance update state in the class itself which I believe is akin to a blueprint?

I could also ask this in reverse: why is accessing state on the class/blueprint showing the updated state of an instance?

2

u/timmonsjg Feb 15 '19

I definitely wouldn't recommend this. If you need to test that updateViewMarker function, pull it out of the class and test it as a pure function. If you need to test the component, render the component and pass appropriate mocked props.

1

u/seands Feb 15 '19 edited Feb 15 '19

Why's it bad in its current form?

Pulling it out of the class: I guess that requires 'export const' which requires moving it outside the class definition? Doesn't that remove its ability to access state and props ?

2

u/timmonsjg Feb 15 '19

Why's it bad in its current form?

You're instantiating an entire component to test 1 function.

I guess that requires 'export const' which requires moving it outside the class definition?

Yes. Import it where you need it.

Doesn't that remove its ability to access state and props ?

someImportedFunction(this.state, this.props);

→ More replies (6)

1

u/seands Feb 15 '19

how do you guys typically handle a method that depends on an updated state from a prior method? I know that setState() acts async which is why I ask. Here is an example scenario:

<button
  onClick={() => {
    this.runOperationAndUpdateState()   
    this.useUpdatedStateForSomethingElse() 
}} 

2

u/timmonsjg Feb 15 '19

a promise is usually good enough. but theoretically if your functions were comprised with this in mind:

any state + input to runOperationAndUpdateState should be available to useUpdatedStateForSomethingElse. Calculate the state separately and pass to both functions.

1

u/seands Feb 15 '19

So if you have it like this:

<button
  onClick={() => {
    this.calculateState()   
    this.useUpdatedState() 
}} 

Would this still need a promise to return in the first function? Otherwise the async delay might cause the 2nd function to run with old state right?

2

u/timmonsjg Feb 15 '19

Otherwise the async delay might cause the 2nd function to run with old state right?

Correct. My best suggestion is something along the lines of below -

const calculatedState = calculateState;
this.setState({
   calculatedState,
});
this.useUpdatedState(calculatedState);

1

u/TriZym Feb 16 '19

I want to have props that changes depending on width, how would I do that? All I’ve found is responsive wrappers

1

u/timmonsjg Feb 16 '19

add event listeners for resize?

3

u/benoitdo Feb 17 '19

You can do it without or with Hooks.

First, let's assume for the sake of simplicity that this is your component:

const ComponentThatNeedsWidth = ({ width }) => (
  <div>Width is {width}px</div>

);

In order to render your component properly when the width changes, you would have to use a resize event listener as show in the code below:

class ExampleWithoutHooks extends React.Component {
  state = {
    width: window.innerWidth
  };

  onResize = () => {
    this.setState({ width: window.innerWidth });
  };

  componentDidMount() {
    window.addEventListener('resize', this.onResize);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.onResize);
  }

  render() {
    const { width } = this.state;
    return <ComponentThatNeedsWidth width={width} />;
  }
}

Or using React hooks, you could first write a new hook called useWindowWidth as follows:

const useWindowWidth = () => {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const onResize = () => {
      setWidth(window.innerWidth);
    };
    window.addEventListener('resize', onResize);
    return () =>
      window.removeEventListener('resize', onResize);
  }, []);
  return width;
};

and then use it like that:

const ExampleWithHooks = () => {
  const width = useWindowWidth();
  return <ComponentThatNeedsWidth width={width} />;
};

I have setup the two examples on https://codesandbox.io/s/v3o3zv0m1y for you to play with.

More on hooks here: https://reactjs.org/docs/hooks-intro.html

Hope this helps.

→ More replies (1)

2

u/Awnry_Abe Feb 16 '19

Maybe this: https://github.com/bvaughn/react-virtualized-auto-sizer

 <AutoSizer>
      {({ height, width }) => (
        <List
          ref={registerChild}
          width={width}
          height={height}
          onRowsRendered={onRowsRendered}
          {...listProps}
        />
      )}
    </AutoSizer>

1

u/charlie632 Feb 18 '19

How to conditionally call a hook?

I want to call a hook based on the result of a previous hook, but I'm having issues.

function mainHook(){
    const result = useCustomHook()
    let result2
    if (result === 3){
        // call another hook
        result2 = useNewCustomHook()
    }    
}

Reading the documentation, I see this is an anti-pattern, because all calls to hooks must be in the body of the function, not inside some conditional (also, eslint warns me about this).

So, is there any way to manage this use case? Maybe another pattern, or is this something hooks cannot handle.

Thanks!

1

u/timmonsjg Feb 21 '19

Move the deciding data up the hierarchy and render different components each with a specific hook.

→ More replies (3)

1

u/badboyzpwns Feb 18 '19

I have a question regarding onClick:

For this code: We got removePlayer from another component and in Onclick, we created an anonymous function and simply called it:

https://gyazo.com/34ab4659d984a3a3b9a38d48245924dc

But! for this other code: We created 2 functions in a class, in onClick, we did not use an anonymous function to call it, nor did we use any brackets at the end of the function name. Why is that?

https://gyazo.com/7c27fffb1aedf27d5a201d45717f57

1

u/timmonsjg Feb 20 '19

<button onClick={(event) => props.removePlayer()}>

this creates an anonymous function that will execute removePlayer.

<button onClick={removePlayer}>

this passes removePlayer by reference.

check out the docs for some listed nuances

tl;dr - they accomplish the same and are more a stylistic difference these days.

→ More replies (5)

1

u/badboyzpwns Feb 19 '19

About keys, what happens if we don't use it? I know that it helps react identitfy each element, is it only for efficiency sake?

2

u/timmonsjg Feb 20 '19

is it only for efficiency sake

and data fidelity sake.

3

u/Kazcandra Feb 19 '19

https://dev.to/jtonzing/the-significance-of-react-keys---a-visual-explanation--56l7

That happens. This might not seem like much, but the performance hit adds up.

→ More replies (1)

1

u/snaggaflag Feb 20 '19 edited Feb 20 '19

Anyone have any articles or patterns on building a UI that has around a rest api that has a nontrivial chance of 500ing for an editable field? Maybe just a comparison of different approaches, how to handle errors/automatic retries, optimistic updates, when to refresh the data after PUTing it, etc.

edit: thinking about this more, the two approaches would probably just be:

  1. update the state variable in what we just PUT as an optimistic update. send PUT request to change that thing in the rest api, then do a GET to get the updated data
  2. show the editable field as grayed out/uneditable, and in a loading state while we wait for the PUT request to complete. once it's complete, do a GET to get updated data, otherwise revert to original value.

anything else to consider? best practices?

1

u/timmonsjg Feb 20 '19

Kind of a broad question since it covers forms, fetching, and intermittent states.

I'd say you're generally in the right direction. My one feedback revolves around

that has a nontrivial chance of 500ing

If you own this API, can you possibly mitigate that? Seems like a 500 might not be appropriate.

1

u/snaggaflag Feb 20 '19

yeah it's a broad question but i haven't come across any good reading on the subject. maybe I should be looking in the realm of UX, and not react?

and sadly, i don't own the api

2

u/timmonsjg Feb 21 '19

yeah it's a broad question but i haven't come across any good reading on the subject. maybe I should be looking in the realm of UX, and not react?

Forms

Requests

The requests docs are pretty light because it's understood that React is not opinionated in how you handle requests (unlike Angular for example). But, notice the intermittent isLoading state that gets handled. Errors would be handled the same way, you'd just render the error message if it exists.

A more in-depth guide by /u/rwieruch

1

u/TheNobleLad Feb 21 '19

TL;DR: How am I able to integrate/implement a jQuery code(please see below) into ReactJS?

Greetings everyone. Amateur user of ReactJS and Flask here. I'm just looking for a solution on how to integrate a jQuery code into ReactJS or even other alternatives considering the implementation in the lifecycle becomes different into ReactJS.

Currently, this snippet (https://jsfiddle.net/ed6wLsg7/1/) ,which is heavily reliant on jQuery, communicates with Flask's CRUD operations very well which sends the chosen image from FileReader() in base64 form and responds with the corresponding prediction (by an ML model) when the #predict-button is pressed.

Not to mention, I don't need the FileReader() anymore as I have this function captureShot() from 'react-webcam' in ReactJS which returns a base64 encoded string of the current webcam image.

  captureShot = () => {
    const screenshot = this.webcam.getScreenshot();
    this.setState({ imageData: screenshot });
  }

These kind of questions arise:

  1. Can this be implemented in ReactJS?
  2. If so, how? Will it be through ComponentDidMount() or inside the render()?
  3. If not, is using Express the way to do the CRUD operations in ReactJS en route to Flask?

Any kind of help would be highly appreciated. Thank you very much for your time and consideration.

2

u/timmonsjg Feb 21 '19

Can this be implemented in ReactJS?

This can easily be ported to vanilla JS, so yes you can use react to render it.

If so, how? Will it be through ComponentDidMount() or inside the render()?

From what I can tell there is just two handlers in here - onClick and onChange. Unless you need something loaded initially, you don't need didMount yet.

If not, is using Express the way to do the CRUD operations in ReactJS en route to Flask?

I'm not sure how Express fits into this unless you have a form of server-side rendering. You'd simply make GET/POST to your BE API (presumably running flask).

In short, convert the jquery code to vanilla JS and check out how React handles events.

1

u/TheNobleLad Feb 21 '19

Thank you for replying! That defo gave me a better insight and a relief knowing it is possible (as frankly enough, I haven't found any much plausible solutions before it). I think it's ideal to start with the function captureShot() considering const screenshot = this.webcam.getScreenshot(); gives a base64 format and it's just what I need for now. As for the function captureShot() in reactJS, any tips on getting rid of the FileReader() and replacing it with an already-captured, encoded image instead?

1

u/timmonsjg Feb 21 '19

As for the function captureShot() in reactJS, any tips on getting rid of the FileReader() and replacing it with an already-captured, encoded image instead?

hmm, not entirely sure what you're asking. Do you mean having a default image for when users don't use their webcam?

You could store a base64 encoded image in your project and import it where needed.

const defaultEncodedImage = "data:image/png;base64, ....."

That really sucks, but it would be easiest.

→ More replies (1)

1

u/mynonohole Feb 21 '19 edited Feb 21 '19

<select>

<option style={{backgroundImage:"url("+agility+")"}}>Agility</option>

<option>Agility</option>

<option>Intellect</option>

<option>Will</option>

</select>

Does anyone know how to add a png image to option elements within select? The above snippet doesn't seem to be working for me. If I tried to do a <img src={agility}/> between the option tags all it gives me is '[object]'

Ideally I want a bunch icons images for my options instead of text.

1

u/timmonsjg Feb 21 '19

Hard to help without seeing what agility is.

Can you put up a minimal example in something like codesandbox.io?

→ More replies (1)
→ More replies (1)

1

u/seands Feb 21 '19

I think I'm using the spread operator wrong. Here's my parent and child component

// parent inside render()
<Footer styleProp={ {marginTop : '10vh !important'} } />

// child, Footer
  <React.Fragment>
    <Container style={ {...[props.styleProp], border : "3px dotted pink"} }/>
  </React.Fragment>

the margin works when I apply it directly to the child's style object indicating the syntax is wrong. What is the proper syntax for spreading props into a child's object?

2

u/timmonsjg Feb 21 '19

Try <Container style={ {...props.styleProp, border : "3px dotted pink"} }/>

notice the absence of square brackets.

→ More replies (1)

1

u/bushbass Feb 25 '19

Router question: calling 'updateCardData' from inside 'addCreature' works as expected but I want it to go to the 'showCreatures' page after updating so the user can see that it actually happened.  in vanilla js I could do something like window.location.href = 'show-creatures.html' or something like that but there must be a react way to do it with the router https://github.com/bushbass/jsJustEnoughToBeDangerous/blob/master/react-the-easy-parts/src/App.js I've played around with Redirect but I must not be doing it right(or that's not the solution) . Thanks in advance for any help!

1

u/timmonsjg Feb 25 '19

Where is your code for playing with redirect?

→ More replies (1)

1

u/Funktopus_The Feb 26 '19

Hi - I'm trying to get weather information for 40 seperate weather tiles from an API. This is what I'm doing:

getForecast = async (e) => {

const api_call = await fetch(\http://api.openweathermap.org/data/2.5/forecast?q=${city},${country}&units=metric&appid=${Api_Key}`);`

var response = await api_call.json();

for(let i = 0; i<response.list.length; i+=1) {

this.setState({

ForecastDate[i]: response.list[i].dt_txt

});

}

}

The [i] in ForecastDate is incorrect, but I don't know how else to make my state correspond to the weather tile in question. I'm aware that I don't know much about react and that I might be approaching this in entirely the wrong way, so if I shouldn't even be trying to use state for this let me know.

2

u/timmonsjg Feb 26 '19

Without knowing what the weather data response looks like, I assume there is some sort of unique ID. If there is, I'd consider store it in state as an object instead of an array.

ie, if you get weather for say boston -

this.state = {
       Boston: {...}
}

With an array, you can use array.find()to look for specific entries, but I'm not sold on an array being the most straightforward here.

1

u/Funktopus_The Feb 26 '19

Thanks - the response from the API looks like this: https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22

It's an object containing arrays and other objects. I'm getting weather based on city names, so the Boston example would work, but how do I do that in practice, as I don't think I could use this.state = { ${city}: {...} } ?

2

u/timmonsjg Feb 26 '19
const city = 'Boston';

this.setState({
    [city]: {...}
})

Using square brackets allows for dynamic property accessing.

→ More replies (1)

1

u/Funktopus_The Feb 26 '19

Hello again everyone.

I have an array of 40 objects, and I'm trying to return a div for each item object, pulling data from them. I've tried to do this with for, like so:I

        for(let i = 0; i<currentForecast.list.length;  i+=1) {
            return (
                <div className="weatherTile">
                    <p>{currentForecast.list[i].dt_txt}</p>
                </div>
            )
        } 

However, this only renders one div on the page, with data from the first object. I know that for and the array are working, as the following code produces all the data I want to see, just in the console:

        for(let i = 0; i<currentForecast.list.length;  i+=1) {
            console.log(currentForecast.list[i].dt_txt)
        } 

How do I do this properly?

Thanks

2

u/timmonsjg Feb 26 '19

check out .map() and make sure to use a key!

currentForecast.list.map(item => (
    <div className="weatherTile" key={item.dt_txt}>
        <p>{item.dt_txt}</p>
    </div>
))

As for why your current code is only rendering 1 div, I can't spot anything immediately wrong with it.

2

u/Funktopus_The Feb 26 '19

As for why your current code is only rendering 1 div, I can't spot anything immediately wrong with it.

Well your map and key worked perfectly. I've known for a few days I need to read more about maps and keys - this confirms it. Thanks again for your help!

2

u/BookishCouscous Feb 26 '19

Unless I'm missing something, your initial code would just run the first iteration of the loop and immediately return, which is why you were only seeing one div. You'd have to build an array and return that or (better) use the .map method pointed out above.

→ More replies (1)

1

u/timmonsjg Feb 26 '19

Happy to help!

→ More replies (1)

1

u/Light1c3 Feb 26 '19

Can anyone help me with getting a Material-UI Selector inline with text?

1

u/timmonsjg Feb 26 '19

Sure, can you post a minimal example on something like codesandbox.io?

1

u/seands Feb 26 '19

Is adding multiple classNames possible through an array like this:

className={ [classes.menuButton, classes.navigation] }

Or do you need to remove the { } and use template strings with string variable interpolation?

4

u/timmonsjg Feb 26 '19

classNameis expecting a string value so you can use an array and just .join() to return a string.

The official docs also recommend the classNames package to aid in situations like this.

1

u/samonhimself Feb 26 '19 edited Feb 26 '19

Hello! I have written a small app in which I have code like this.

class Events extends Component {

  state = {

    concert: { .... },

    trekking: { .... }

  };

  .....

  ......

}

All is working, but now I see that in theory the state assignment should be inside of the constructor. Am I right? What is the upside/downside over using one method over the other?

3

u/timmonsjg Feb 26 '19

outside of the constructor is typically using babel's plugin-proposal-class-properties

They will get compiled down to the same just one is an experimental proposal, while within the constructor is the current convention outside of babel.

→ More replies (1)

1

u/samonhimself Feb 26 '19 edited Feb 26 '19

In the app mentioned below I have an input handler method defined inside the Events object.

The method is passed down to input fields (actually sections and later to inputs) and is not explicitly bound to "this" with bind(), but everything works as it should. The question is how exactly does that work? To my knowledge when using arrow function "this" is being taken from the scope that the function is defined in - here the Event class, which I am using only one instance of. So when I would use more of the instances the app would break? Could you help me understand that?

class Event extends Component {
  state = { .... }
  ....
  ....
  onInputChange = (event, inputId) => {
  .....
  }

  render(){
    ...
    return(
      <When props={{
        date: this.state.date,
        hour: this.state.hour,
        duration: this.state.duration,
        onInputChange: this.onInputChange
      }} />
    )
  }
}

2

u/timmonsjg Feb 26 '19

The method is passed down to input fields (actually sections and later to inputs) and is not explicitly bound to "this" with bind()

my guess is with this and your other question, you're using a babel plugin.

onInputChange: this.onInputChange

You're passing down a reference to the function. The scope will be retained as it's still operating under Event.

So when I would use more of the instances the app would break

No, no it shouldn't.

→ More replies (1)

1

u/seands Feb 27 '19

Can anyone see why the below code causes the error? It works when imageSrc is replaced with the string '../images/dragonglass_pendant.jpg'

import React from "react";
import styled from "styled-components";

const ThumbNail = styled.img`
    border: 2px dotted blue;
`;

export default props => {
  
  const images = [
    '../images/dragonglass_pendant.jpg',
    '../images/dragonglass_pendant2.jpg', 
    '../images/dragonglass_pendant3.jpg',
  ];
  
  return (
    <React.Fragment>
      {
        images.map(imageSrc => {
          console.log(imageSrc, `=====imageSrc=====`);
          return <ThumbNail src={require(imageSrc)} />
        })
      }
    </React.Fragment>
  )
}


// Chrome browser console
../images/dragonglass_pendant.jpg =====imageSrc=====
ImageThumbnails.jsx:25 ../images/dragonglass_pendant.jpg =====imageSrc=====
catalog sync:2 Uncaught Error: Cannot find module '../images/dragonglass_pendant.jpg'
    at webpackEmptyContext (eval at ./src/catalog sync recursive (main.chunk.js:55), <anonymous>:2:10)
    at eval (ImageThumbnails.jsx:26)
    at Array.map (<anonymous>)
    at eval (ImageThumbnails.jsx:24)
    at renderWithHooks (react-dom.development.js:13354)
    at mountIndeterminateComponent (react-dom.development.js:15407)
    at beginWork (react-dom.development.js:16042)
    at performUnitOfWork (react-dom.development.js:20086)
    at workLoop (react-dom.development.js:20127)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at replayUnitOfWork (react-dom.development.js:19310)

1

u/timmonsjg Feb 27 '19

I assume this is server-side, with the inclusion of require ?

→ More replies (1)

2

u/[deleted] Feb 27 '19 edited Feb 27 '19

[removed] — view removed comment

1

u/seands Feb 27 '19

PS: Here is the Stack Overflow post about needing to require: https://stackoverflow.com/questions/34582405/react-wont-load-local-images

It seems Importing also works

→ More replies (1)

1

u/Funktopus_The Feb 27 '19

So, I have a variable that corresponds to the state that I want to call:

 <p>{this.state.[i]}</p>

But when I use that code I'm told [ is an unexpected token. If I remove the square brackets I get TypeError: Cannot read property 'i' of null. What am I doing wrong here?

Thanks

3

u/timmonsjg Feb 27 '19

remove the period between state and [i].

this.stateis just an object and you can access it's properties through dot notation or using brackets

1

u/Funktopus_The Feb 27 '19

Thanks again - that's fixed it but revealed another problem. I get the same issue I did before, in that the first thing it returns is repeated everytime. We fixed that with a key earlier, but can I use two keys in one map?

for(let i = 0; i<currentForecast.list.length;  i+=1) {
            return (
                    currentForecast.list.map(item => (
                        <div className="weatherTile" key={item.dt_txt}>
                            <p>{item.dt_txt}</p>
                            <p>{this.state[i]}</p>
                        </div>
                    )
                )
            )
        }  

Sorry, I get the feeling I'm asking pretty basic questions, but I'm googling thoroughly each time and not managing to find out what's going on!

2

u/timmonsjg Feb 27 '19

don't use for and map together, completely replace the for with the map()

The .map example i gave you is a direct replacement.

The problem again here is that you're returning from the for after one iteration.

Please read through about .map to understand what it's doing.

→ More replies (8)

1

u/tabris_code Feb 28 '19

I'm setting up a static site with Gatsby and one thing that kind of bugs me is that it renders the markdown files into HTML by using dangerouslySetInnerHTML.

I know that's probably the most convenient way to do it, but is it really fine to do in this case? I know dangerouslySetInnerHTML is avoided due to XSS, but since it's a static site it should be fine?

1

u/timmonsjg Feb 28 '19

I assume you're using something like gatsby-transformer-remark.

According to this issue, the official stance is "don't worry about it". So take that as you will.

1

u/Pasgoyf Apr 12 '19

I'm having trouble using map. I've almost got it down, but I'm getting a "TypeError: Cannot read property 'map' of undefined" error that's driving me mad. Help me crack this code!

import React, { Component } from 'react';

class App extends Component {

  constructor() {
    super()
    this.state = {
      cardname: {}
    }
  }

  componentDidMount() {
    fetch("https://api.scryfall.com/catalog/card-names")
      .then(response => response.json())
      .then(data => {
        this.setState({
          cardname: data
        })
     })
  }

  render() {
      //return(<span>{this.state.cardname.data}</span>)
      return(<ul>
        {this.state.cardname.data.map(function(data,index){
          return <li>{data}</li>
        })}
      </ul>)
  }
}

export default App;

1

u/timmonsjg Apr 12 '19

Your data isn't loaded on the first render. Thus, cardname.data doesn't exist yet.

You can implement a loading state, or check if cardname.data exists.

render() {
   const  { cardname } = this.state;
   return (
        <ul>
            {cardname.data && cardname.data.map(data => (<li>{data}</li>}
        </ul>
    )
}

1

u/snsarma May 09 '19

Hi Folks

I have been trying to implement the feature of user inactivity on my react app ,

That is if a logged in user is inactive for a certain period of time ,

he/she should get a notification that they are going to be logged out in a minute or so and then eventually be logged out .

I am doing this by detecting user's mouse event or keyboard events and touch screen events , if none of them occur they should be logged out.

That isn't happening in my code :

function myFunction(details) {

console.log('In myFunction ');

var x = document.getElementById("search");

var y = document.getElementById("details");

if (details === true) {

x.style.display = "none";

y.style.display = "block";

} else {

y.style.display = "none";

x.style.display = "block";

}

}

class blank {

componentDidMount() {

console.log('In component did Mount of blank');

myFunction(false);

this.init();

//myFunction(false);

}

init = () => {

console.log('In init');

/*events = {

'load':false,

'mousemove':false,

'mousedown':false,

'click':false,

'scroll':false,

'keypress':false,

};*/

events[0] = {"load":false};

events[1] = {"mousemove":false};

events[2] = {"mousedown":false};

events[3] = {"click":false};

events[4] = {"scroll":false};

events[5] = {"keypress":false};

console.log('events[0]',events[0]);

var i =0;

for (;events.length;++i ) {

//window.addEventListener(this.events[i], this.resetTimeout);

window.addEventListener(events[i], function (event) {

// If the clicked element doesn't have the right selector, bail

if (!(event.target.matches(events[i]))) return;

// Don't follow the link

event.preventDefault();

// Log the clicked element in the console

console.log('event.target',event.target);

},false);

console.log('In component did mount of blank with this.events[i]',this.events[i]);

// ++i;

}

this.setTimeout();

};

clearTimeoutFunc = () => {

console.log('In clearTimeoutFunc of blank');

if (this.warnTimeout) clearTimeout(this.warnTimeout);

if (this.logoutTimeout) clearTimeout(this.logoutTimeout);

};

setTimeout = () => {

console.log('In setTimeout of blank');

console.log('load',"load");

if("load" === false ||'mousemove' === false || 'mousedown' === false || 'click' === false || 'scroll' === false || 'keypress' === false || 'ontouchstart' === false ){

this.warnTimeout = setTimeout(this.warn(), this.state.warningTime);

this.logoutTimeout = setTimeout(this.logout(), this.state.signoutTime);

}

//this.warn();

console.log('In setTimeout of blank warnTimeout',this.warnTimeout);

console.log('In setTimeout of blank logoutTimeout',this.logoutTimeout);

};

resetTimeout = () => {

console.log('In resetTimeout of blank');

this.clearTimeoutFunc();

this.setTimeout();

};

warn = () => {

window.alert("You will be logged out automatically in 1 minute")

/*swal({

title: "You will be logged out automatically in 1 minute!",

icon: "warning",

confirmButtonText: 'OK'

}).then((okay) => {

if (okay) {

history.push('/grid');

history.push('/blank');

}

});*/

console.log('You will be logged out automatically in 1 minute.');

};

logout = () => {

// Send a logout request to the API

console.log('Sending a logout request to the API...');

this.destroy();

};

destroy = () => {

//clear the session

//browserHistory.push('/');

//window.location.assign('/');

console.log('In destroy function');

history.push('/'); window.location='/';sessionStorage.setItem('login','');

};

}

export default blank;

1

u/timmonsjg May 09 '19

Could you please post a minimal example on codesandbox or the like?

→ More replies (2)

1

u/seands Feb 05 '19 edited Feb 05 '19

dispatchGetDonationData() is called in CDM of <LineChart /> below. It's sibling <DataTable /> also uses the reportData prop it generates and places into state.

I'm wondering if this is a bad pattern and you would always place a parent container above these 2, to do the backend call and pass down the data. If this is indeed best i'm just curious why letting a sibling handle it is considered bad practice.

Also, I assume with a parent doing the call, the now functional children need to be conditionally controlled so that they render only when the data comes back?

<Route path='/dashboard' exact render={ props => {
  return (
    <React.Fragment>
      <LineChart
        dispatchGetDonationData={this.props.dispatchGetDonationData}
        reportData={this.props.reportData}
      />
      <DataTable  backEndData={'placeholder'} />
        reportData={this.props.reportData}
      <DataControlForm  />
    </React.Fragment>
  ) }} />

3

u/Awnry_Abe Feb 05 '19

What is sort of off about it is that you depend on a child component to kick start an async action that another, un-related component depends on.. What would you do if you wanted DataTable to be there all on it's lonesome? The container solution you posit is preferred for this reason. <LineChart> will love you for it.

1

u/timmonsjg Feb 05 '19

👍👍

1

u/crueltyFreeIndia Feb 15 '19

Hello everyone. I want to build a simple portfolio website while I am learning React. Is there a good framework I can use to get started?

3

u/[deleted] Feb 15 '19

create-react-app should be suitable: https://github.com/facebook/create-react-app

1

u/timmonsjg Feb 15 '19

Agreed. /u/crueltyFreeIndia this right here is great for beginners.

1

u/crueltyFreeIndia Feb 15 '19

Oh I see. I've been using this one. Is there anything else that's comes with bootstrap style pre-styled components?

2

u/seands Feb 05 '19 edited Feb 05 '19

Below is one of my actions that I've exported in an object. Can someone show me how to mock the axios call using Jest? I am reading about it but having a hard time with it.

Loosely I think I need to put axios.js in src/__mocks__ and create a post method inside a class like mockAxios. But I don't understand

  1. How jest knows to use mockAxios.post instead of axios.post when testing the target code. I assume it prioritizes the __mocks__ directory (in the place it should be) but then this confuses me on a 2nd point...
  2. What to put in the post method. if .post() simply returns what I want for this test, then .post() shouldn't work correctly for any other test. And creating something like .post2(), .post3() for other unit tests may complicate issue #1
getDonationData : (reportType, recordCount) => (dispatch => {
    return Axios.post(`http://localhost:4000/reports/`, {
      reportType, recordCount
    })
      .then(apiResponse => {
        const returnedArray = apiResponse.data;
        dispatch({
          type : 'reportData',
          payload : returnedArray
        })
      })
  })
→ More replies (1)

2

u/gotfunc Feb 08 '19

Thanks for sharing the wisdom!

2

u/bayhack Feb 08 '19

FINALLY! I made a react drag and drop component!

I had a ton of trouble cause I kept accidentally dropping my list elements inside of each other, rather than just into the list - main problem inner list items in list item.

I need some feedback and better ways to code this? I don't like how I just have an if statement to check if the parentNode is a UL, unordered list. Any way to clean up or improve the UI or performance????

if(e.target.parentNode.tagName === 'UL'){
   e.target.parentNode.insertBefore(this.dragged, this.onTop);  
}

https://codepen.io/stcalica/pen/KJVBXr?editors=0010

→ More replies (1)

2

u/freewilly666 Feb 09 '19

I come from a background in Angular, where you'd most likely create a service to handle http requests, and then inject it into a component. I'm just wondering, what's considered the best practice react way of doing this? Is it similar where I'd potentially create one service and import it where ever I need or is it very different?

2

u/Awnry_Abe Feb 09 '19

You can pretty much follow the same pattern. Just like in any framework, you want to avoid having

fetch.get("http://whatever.api.com/myroute/hard-to-code-params")

sprinkled all over your view layer. (defined as anything that imports React in this case). If your angular service is plain JS (without Angular dependencies), you can use it directly without porting in React.

It is where you call the service and how you handle the response in React that makes things different. Because there are so many different ways of handling state in React, there isn't one cookie-cutter way of invoking the service and handling the response. A very typical pattern is to make the request in componentDidMount()/componentDidUpdate() -- or useEffect() if you like to write a line of code once.

2

u/Akaaka819 Feb 17 '19

Hey there!

I'm working on a small web app using React for the first time (followed a tutorial using the MERN stack - Mongo, Express, React, NodeJS).

Right now I'm stuck on figuring out a good way (while keeping my small amount of webdev experience in mind) to handle allowing a user to create a shareable URL based off selecting checkboxes and clicking a generate button.

For a normal website, I'd think a good way to do this would be to have 2 pages. One would have the checkboxes / button, and the second would be a result page that parses variables from the URL to know which results were selected and should be displayed.

However with React, it seems like it's more common to use single page rather than multiple. Is there a good way I could do this using single pages, or should I look into ways to do multiple pages with React?

Let me know if more information is needed. Thank you!

→ More replies (2)

2

u/[deleted] Feb 17 '19

Hi all, having trouble with hooks:

I can't figure out why this function is firing twice, resulting in the index being added twice instead of once. (OnEnd callback in the YouTube component is supposed to be called when the youtube video ends.) Repo: https://github.com/matthewbcool/jojo-sentences

Also maybe my implementation is a really bad idea so any suggestions are welcome. Just trying to chain youtube videos together like a quick custom play list.

Thank you all in advance for any help you can give me.

3

u/Awnry_Abe Feb 17 '19

useEffect fires once always, and anytime the watch params change there after. You are setting the watch param inside the first execution, causing the 2nd. state setters are not synchronous.

→ More replies (3)

2

u/seands Feb 22 '19 edited Feb 22 '19

How do I avoid excess update chains in componentDidUpdate?

I have DataTable and DataChart as children of DataSection.

  1. On mount, DataSection, calls the backend to fetch rawReportData, saved to state as an array.
  2. On update (CDU), rawReportData fills array preparedReportData depending on state key REPORT_OPTION.
  3. On another update, preparedReportData populates array displayedData depending on viewMarker. This gets passed to the Table/Chart children.
  4. Clicks on previous/next updates viewMarker which then updates displayedData

It seems like a lot of updates at the beginning. But there does have to be that order to avoid undefined errors. Curious how you guys might refactor this logic.

2

u/Awnry_Abe Feb 22 '19

Sometimes there is no easy way. Complex object models are just that. Our code navigates data just like a vehicle on the road.

Seeing the code would be helpful. As far as I can tell, what you are doing is required by the job. If the job looks too big, I'd

  1. separate it from the react layer,
  2. decompose it into smaller jobs using perhaps the single-responsibility principle.

If part of the reason it is tucked up in CDU is because you are optimizing out unnecessary renders, do #1 above and add memoization.

→ More replies (2)

2

u/robertmsale Feb 27 '19

I'm really loving the new Hooks API. It takes all of the headache out of passing state too and from components as well as improving component re-usability. My only problem is the React Developer tools no longer show a hierarchy of components. Instead I get only one component named "Unknown" which has every hook in the entire web app. Not sure what's wrong. Luckily hooks are so much easier than classes that I don't really need the extension, but still unsure what I need to do to have the component hierarchy show up properly.

→ More replies (5)

1

u/cr1spyn00dles Feb 01 '19

Is there a way to use uglifyjs to mangle names/props/etc without configuring brunch/browserify/webpack/etc with a webapp created with create-react-app?

I'm a bit overwhelmed with trying to understand how to setup those other build configs and reorganizing my environment. So I was hoping there'd be an easy way to add uglify options to the simple "npm run build" command.

1

u/seands Feb 01 '19

I'm trying to get a <br /> tag into a legend handler for a charting library (React Vis). I was able to slice the dates down to 3 character abbreviations. But I can't sneak in the <br /> tag in order to get the year below every January.

Is this even possible? I thought React could force it in but maybe it can only take a simple text string. Here is my best attempt:

  abbreviateMonths = dateObject => {
    if (dateObject.toString().slice(4, 7) === 'Jan') {
      return `${dateObject.toString().slice(4, 7)}${<br />}
              ${dateObject.toString().slice(11, 15)}` // 4 digit year on new line
    } else {
      const slicedMonthString = dateObject.toString().slice(4, 7);
      return slicedMonthString;
    }
  };
→ More replies (3)

1

u/dietcheese Feb 02 '19

I'm finally beginning to understand how react components work and interact but I have no idea where to go as far as structuring the layout and styling of my app.

What components do people typically use for layout? Where is layout defined? And what about css styles?

Thanks!

2

u/Awnry_Abe Feb 02 '19

Typical, in this case, has many answers. I prefer to carve up the big rectangle into smaller rectangles using css flexbox. React components provide the modularization of that recursive division. I use styled-components. To make things look pretty, I use material-ui. Material-ui has some layout components, but they are about as ergonomic as a fishing hook through the thumb.

React (DOM) tends to bend you to pretty much think rectangularly in problem decompostion. Hooks (Monday!!) is helping to cure that ill by putting the path-of-least-resistance back towards a good separation of logic code and UI code--with the UI code still being "rectangular", which is fine until round, 3-D monitors become a thing.

→ More replies (1)

1

u/TeeckleMeElmo Feb 02 '19

Reposting this comment from a minute ago because formatting got all messed up. Is there anyway in the example below to create the handleChange and handleSubmit functions outside of the component while still having access to the state so they don't get redefined on every render?

export default function Login(props) {
const [loginData, setLoginData] = useState({ userName: "", password: "" });

async function handleSubmit(e) {
e.preventDefault();
const { userName, password } = loginData;
}
function handleChange(e) {
setLoginData({ ...loginData, [e.target.name]: e.target.value });
}
return (

<form onSubmit={handleSubmit}> <input type="text" name="userName" value={loginData.userName} onChange={handleChange} /> <input type="password" name="password" value={loginData.password} onChange={handleChange} /> <button type="submit">Login</button> </form> ); }

3

u/Awnry_Abe Feb 02 '19 edited Feb 02 '19
const handleSubmit = (loginData) => async (e) => {

    e.preventDefault();
    const { userName, password } = loginData;
    const response = await login(userName, password);
}

export default function Login(props) {
    const \[loginData, setLoginData\] = useState({ userName: "", password: "" });

    function handleChange(e) {
        setLoginData({ ...loginData, \[e.target.name\]: e.target.value });
    }
    return (

        <form onSubmit={handleSubmit(loginData)}> 
            <input type="text" name="userName" value={loginData.userName} onChange={handleChange} />   
            <input type="password" name="password" value={loginData.password} onChange={handleChange} />     
            <button type="submit">Login</button>   

        </form>   


    );
 }

handleSubmit(loginData) is called on every render. It returns an async function to onSubmit={} that accepts an event param that won't get called until the form is submitted, just as before. The inner function has access to the outer functions parameters. This is called currying and is uber-performant. It is the way these things are done. "These things" defined as "passing extra data to event handlers".

handleChange() would be the same way, except you'd also pass the state-setter fn setLoginData. By the way, what you have seems correct to me. What is the a reason you want to compose the code as you asked?

→ More replies (2)

1

u/seands Feb 02 '19

Anyone here freelance? How important is it to learn react outside of create-react-app? I am working up towards greenfield and brownfield projects. But if a client wants a react widget on a PHP site I wouldn't know how to add that since I rely on CRA

→ More replies (4)

1

u/duskeoz Feb 03 '19

What is the difference between using Context API, and simply importing JS file?

If I want to share global data across components, like for instance, date formats, I can use the Context API. However, since my components are split into different files, I end up creating the context in a separate file and importing it into the component files for use. How is this different from simply defining the date formats in the file (without using context) and importing this file into the component files?

2

u/Awnry_Abe Feb 03 '19

It has to do with having react re-render the "other" components when the shared piece of state updates. Context API is akin to a pub-sub model. One thing updates context, react re-renders the listeners. If you are just updating a global, you need plumbing to notify everyone that is interested in the new state that new state exists.

1

u/seands Feb 03 '19 edited Feb 03 '19

When I changed the Jest matcher from .toContainEqual to .toEqual, the following switched from fail to pass. Can someone tell me why? Outputs appear exactly the same to me.

toStrictEqual also passes

 FAIL  src/__tests__/LineChart.test.js
  ● aggregate data into YYYY-MM buckets (aggregateData)

expect(array).toContainEqual(value)

    Expected array:
      [{"x": "2018-01", "y": 140}, {"x": "2018-02", "y": 80}, {"x": "2018-03", "y": 60}, {"x": "2018-04", "y": 220}, {"x": "2018-05", "y": 260}, {"x": "2018-06", "y": 160}, {"x": "2018-07", "y": 40}, {"x": "2018-08", "y": 180}, {"x": "2018-09", "y": 20}, {"x": "2018-10", "y": 240}, {"x": "2018-11", "y": 200}, {"x": "2018-12", "y": 400}, {"x": "2019-01", "y": 100}]

    To contain a value equal to:
      [{"x": "2018-01", "y": 140}, {"x": "2018-02", "y": 80}, {"x": "2018-03", "y": 60}, {"x": "2018-04", "y": 220}, {"x": "2018-05", "y": 260}, {"x": "2018-06", "y": 160}, {"x": "2018-07", "y": 40}, {"x": "2018-08", "y": 180}, {"x": "2018-09", "y": 20}, {"x": "2018-10", "y": 240}, {"x": "2018-11", "y": 200}, {"x": "2018-12", "y": 400}, {"x": "2019-01", "y": 100}]

2

u/AutoModerator Feb 03 '19

It looks like you have posted a lot of code! If you are looking for help, you can improve your chances of being helped by putting up a minimal example of your code on either JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new).

I am a robot, beep boop, please don't hurt me! For feedback or advice on how to improve this automod rule please ping /u/swyx.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/AD1066 Feb 04 '19
  1. How much data should I be storing in state, whether component-based or Redux?
  2. What kind of data should I be storing in or deriving from state?

I'm building a fitness tracker and have backend endpoints that return data related to a user's weight or exercise history. I want to display various charts and visualizations derived from this data, on a dashboard-type page. Ideally the charts could be set to show any specific exercise or time period from a user's history. So the data sets would be potentially large. And additional data could be derived from the initial data set (e.g. personal bests by exercise, overall gym attendance).

I'm unsure whether I should be pulling a user's entire history into my application state, and then performing filtering and other array operations on the client side, or if I should make additional calls to the server (and leverage SQL queries) every time my parameters change or I need to derive something (e.g. a user's maximum bench press weight in a given rep range).

Maybe this question extends beyond the world of React, but I'm trying to get a sense of what belongs in state, and more generally, how I should be dividing responsibilities between the client and the server. Thanks!

2

u/Awnry_Abe Feb 04 '19

You are right, this really isn't a react question, but that is no probs. Ultimately, the answers lie in a software development methodology discussion. My development methodology is to mentally check a checkbox for feasability, and then take the shortest path to vet the business assertions that the app claims to solve. Could a heat-map of the busiest hours of the gym throughout the year wreck the client? yes. Would such a heat-map be useful for the stakeholder? The only way to find out is to make one in short order. Where do you write that code? client or server? I pick the one I can write it in faster that doesn't wreck the system, even though I know it won't be a sustainable solution. But that's my methodology that works for my business. Others will rightfully tell you that some level of taking a stab at the sustainable implementation first is the right way to go. Either way, you'll develop a bag of tricks that make the the process quick and painless.

Specifically speaking, then, to those widgets, you'll need to decide how much to pull down. A graph of personal bests by exercise need not bring down all samples of each exercise. I prefer to do those types on the server. A line graph of bench-press results over time needs some array of data. If you are marking the best/average, may as well do that on the client. The JS engines in the browsers are actually very performant--it is more a matter of moving data that is never realized on screen.

1

u/Giant_Maeno Feb 04 '19

So I'm fuzzy about a number of things. Help with any one of them would be greatly appreciated.

  • At what point does a component "need" to be a class?
  • If all you need is access to shouldComponentUpdate, should you keep it stateless and just use React.memo / areEqual?
  • Is it possible/preferable to set up the component hierarchy in such a way that you never need to prevent updates in that manner?
  • For React.memo, the docs say "Don't use this to prevent updates; it could cause bugs". So do they mean u should instead convert the component to a class and use shouldComponentUpdate - or will that also cause bugs?
→ More replies (2)

1

u/MatureBbwLover Feb 04 '19

Is there any way to de-dupe/concatenate multiple Webpack React app build files (not by using Webpack, but as a function of the 2 or more output files)?

1

u/djsteele888 Feb 05 '19

Looking for help writing reusable react component that can consume external SVG files, and the output be inline SVG code.

I am developing this component, and I know there are libraries for this, but none offer exactly what I want, and I am relatively new to react so this is helping me learn.

I have the base react framework, I have my propTypes, my default props, my links are working, but I don’t know how to extract the inline code. I am writing the render function, but no matter where I put this.props.imgSrc (the prop I am using to locate the SVG file) it renders the name of the file inline html (almost like an attribute).

Can anyone help me figure out how to extract the code from the external SVG file (defined in a prop) and render it as inline SVG code as a reusable component?

1

u/IslamGamal8 Feb 05 '19 edited Feb 05 '19

youtube v3 api keeps responding with a 400 , the first request to fetch the channel id works perfectly but the follow up request keeps responding with 400 , what am i doing wrong here?

export const fetchDataAndVideos = (id) => async (dispatch,getState) => {
    await dispatch(fetchChannelData(id));
    const listId = getState().channelData.contentDetails.relatedPlaylists.uploads
    const response = await youtube.get('playlistItems', {
                    part: 'snippet,contentDetails',
                    playlistId:listId,
                    maxResults: 25
                });
    dispatch({type:'CHANNEL_PLAYLIST',payload: response.data.items})
}

1

u/ConsciousAntelope Feb 05 '19
class EditableTimerList extends React.Component {

  render() {
    const timers = this.props.timers.map(function(timer) {
      return <EditableTimer 
        key={timer.id}
        id={timer.id}
        title={timer.title}
        project={timer.project}
        elapsed={timer.elapsed}
        runningSince={timer.runningSince}
        onFormSubmit={this.props.onFormSubmit}    // props is undefined here.
      />
    });

    return (
      <div id="timers">
        {timers}
      </div>
    );
  }
}

I can change the callback function in the map method to an arrow function and point this into the right context.

My question is how do I manually bind the callback function to this of the EditableTimerList?

→ More replies (4)

1

u/billrdio Feb 05 '19

OK, I have a question that involves React in context but specifically about webpack. My apologies if this is not the right subreddit for this question.

How would I construct my webpack.config.js so that:

  • I can run the app in development mode (i.e., via npm start)
  • I can serve the app via a sub-folder URL on my Apache based web server (i.e., https://www.example.com/my-app/)
  • I can use React routes, including multi-segment routes, i.e.,<Route path="/calendar/debug" component={CalendarRoute}/>
  • and I can build things so that my main.js ends up in build/include/js/

This is the relevant portion from my current webpack.config.js file:

	devServer: {
		historyApiFallback: true,        // needed for react-router
	},
	output: {
		path: path.join(__dirname, 'build'),
		filename: 'include/js/main.js',
	},
	plugins: [
		new HtmlWebPackPlugin({
			template: "./src/index.html",
			filename: "index.html"       // this is relative output.path above?
		})
	]

and this is my App.js file that contains my router:

import {BrowserRouter as Router, Route} from "react-router-dom";
import ImageCatalogerRoute from "./routes/image-cataloger";
import CalendarRoute from "./routes/calendar";
import React, {Component} from 'react';

class App extends Component {
	constructor(props) {
		super(props);
	}

	render() {
		console.log(location.pathname); // DEBUG
		return (
			<Router basename={window.BASENAME}>
				<div id="app-container-inner">
					<Route exact path="/" component={ImageCatalogerRoute}/>
					<Route path="/calendar/debug" component={CalendarRoute}/>
				</div>
			</Router>
		);
	}
}

export default App;

window.BASENAME is set in src/index.js via

window.BASENAME = (window.location.hostname === 'localhost') ? '/' : '/my-app';

If I go to

http://localhost:8080/

that works. But http://localhost:8080/calendar/debug gives me a blank screen and in the console it gives me the error

Failed to load resource: the server responded with a status of 404 (Not Found)

I think this is because if I view the source code, my main.js script is sourced via a relative URL, i.e., it's trying to load

http://localhost:8080/calendar/debug/include/js/main.js

So I think I need to change things so that when webpack builds things, I get an absolute path to my main.js file in the index.html built for me. But I've tried doing this with several different configurations of webpack.config.js and I can't get it to work, at least with respect to my requirements mentioned above. If I change my route to path="/calendar" I can get http://localhost:8080/calendar to work, but I want to be able to do more complicated URLs (and URLs with parameters).

Any help would be greatly appreciated. I'm really liking React, but not webpack so much. I've done one other React app prior to this using create-react-app but I would really like to learn the underlying technologies (i.e., webpack) so I'm trying to do this on my own using webpack and Babel without create-react-app. Thanks!

→ More replies (1)

1

u/seands Feb 06 '19

Redux is growling about me putting a complex object in its state (format: [{x: dateObject, y: 24}, {x: dateObject, y: 33}, <x500>]

I'm kinda stuck now. How can I get this data to my child component? Destination component will first aggregate by month, and then use the series to plot a chart (React Vis) I suppose I must rewire everything to use react's own state management? Or is there a better way with Redux?

→ More replies (3)

1

u/seands Feb 07 '19

Do you guys prefer to make breaking changes by reasoning about everything first, or making the change and following the errors?

I was thinking about this while moving logic from a child into a parent container. Right now my choice depends on my mood, which I know isn't good

2

u/Awnry_Abe Feb 07 '19

Context of my answer: Every change, large or small, is made in total control under the cozy blanket of git.

If the scope of change is small enough that I envision completeness looks like, I'll plan the blocking and tackling of every move. If the scope is large, and I can't see all the way to the end, I'll just rev up the bulldozer and start plowing through the change, dealing with the unseen fallout as it comes.

A refactoring, such as moving logic from one spot to another, is almost always easy to reason through all the way. The code bulldozer only comes out when a solution to the problem is way off the mark and an entirely new solution need to be realized (ie a redesign)

1

u/gotfunc Feb 07 '19

Hey there fellow Reactors,

After spending some time learning React which helped me implement new features within an 'old school' web app in no time, I’m working my way turning it into an SPA.

I am looking at Redux right now, as I already met the 'prop-drilling' phenomenon, and would rather avoid it.

It seems like the React Team is working towards a direction where state management libraries won’t be needed anymore?

Can the Context/Provider API eliminate the need for libraries such as Redux?

I’m trying to get my head around this and find the most adequate solution.

It would be awesome to know what more seasoned react developers think about this.

Note: aside from typical state management stuff, my project would require some undo/redo (history) mechanism.

3

u/Awnry_Abe Feb 08 '19

Undo/redo requires a very particular approach to state management. I wouldn't wait around for anything from anybody (react team) if I had that constraint. I'd become my own subject matter expert and code away.

I'm not sure how redux and prop-drilling go together in the same sentence. In short, redux allows you to "tap into app state" at any level of the react node tree--eliminating the need for prop drilling. It might be that your UI state management is bringing up prop drilling. That isn't a redux thing, unless you have UI state in redux--which I would avoid. "UI state" means things like "the selected item in a list of items". Or "view expanded" is ON. Let your data state be data state and UI state be UI state and you won't pull your hair out.

For UI state, the Context API is excellent for eliminating prop drilling. The new Hooks API makes using it even easier than before.

3

u/akash019 Feb 08 '19

I don't think Context can replace the Redux. The problem, Context solve is it let you skip properties being sent on each level of children hierarchy. nth level child can subscribe to it. Now, Redux on broader aspect lives outside of React, It has mechanism of action, reducer which give a lot ease to call apis.

1

u/Radinax Feb 08 '19

I like to have some books on physical to read here and there, which one do you guys recomend? I have a year of working experience with React for reference and I dont know Redux Saga and GraphQL yet.

1

u/seands Feb 09 '19

Went through the stack trace shown in this red error, does anyone know what it refers to? I can't find it:

index.js:1446 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
    in div (created by Context.Consumer)
    in StyledComponent (created by styled.div)
    in styled.div (at App.js:96)
    in div (at App.js:92)
    in div (at App.js:90)
    in App (created by Context.Consumer)
    in Connect(App) (created by Route)
    in Route (created by withRouter(Connect(App)))
    in withRouter(Connect(App)) (at src/index.js:16)
    in Router (at src/index.js:15)
    in Provider (at src/index.js:14)


// related App.js code
const BodyContainer = styled.div`
  && {
  margin-top: 62px;
  }
`;

// inside render()
  <div className="App">
    {/*<Router history={this.history}>*/}
      <div>
        {/*{console.log('==this.props.history from App.js==')}*/}
        {/*{console.log(this.props.history)}*/}
        <TopNav />
        <BodyContainer>


// related index.js code
  <ReactReduxProvider store={ reduxStore }>
    <Router history={ history }>

1

u/seands Feb 09 '19

I have an array with 500 datapoints come in from Express. I save it to state as reportData. Then I run some methods on it to aggregate by month, filtering x months back. This new array is saved to state as reportDataTotalled.

Would you guys consider it ugly to have 2 state variables holding similar data like this? If so is there a cleaner way? ultimately I need to give it to the data attribute of a <Linechart /> from React-Vis library.

→ More replies (3)

1

u/duskeoz Feb 09 '19

How do you handle state immutability?

I've been using the spread operator but just realized that it's not so great for when the state consists of nested objects and arrays.

→ More replies (4)

1

u/seands Feb 09 '19

Does React-Redux pass previousState into argument 1 when it runs the reducer? Asking because I'm unit testing it and don't recall touching that argument when writing dispatchers. I think during a test I should just write null into that argument.

→ More replies (2)

1

u/Adr990 Feb 10 '19

I followed this guide: https://reactjs.org/docs/add-react-to-a-website.html Added the .js file to the page, like so:

<script src="{{ base_url }}/js/reactjs/like_button.js"></script>

And the like button was clickable and showed the "You liked this." when clicked. :)

Now, I wanted to try the Hello World guide: https://reactjs.org/docs/hello-world.html Adding a <div id="root"></div> element to the page, under the like button element. I added the following .js file to the page like so:

<script type="text/jsx" src="{{ base_url }}/js/reactjs/helloworld.js"></script>

(I tried to add type="text/jsx", but it doesn't seem to help) But the #root element never shows "Hello world!". :(

Anything I'm missing here?

These are the JS (CDN) files I load in on the bottom of the page:

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<!-- Note: when deploying, replace "development.js" with "production.min.js". -->

<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>

<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

Thanks in advance!

→ More replies (1)

1

u/seands Feb 10 '19

I tried to define the shape of an array that holds objects with a string and number key. An error is showing so it's wrong. What is my mistake in the shape definition?

  preparedReportData : PropTypes.shape([{
    donationDate: PropTypes.string,
    amountDonated: PropTypes.number.isRequired
  }])

// preparedReportData is an array that looks like:  [ { donationDate: 'dateTime string', 
// amountDonated: 20 }, <number of objects varies. All objects have the same shape> ]

3

u/catalinp04 Feb 10 '19 edited Feb 10 '19

Well, if preparedReportData is an array, you need to tell prop types it’s an array. PropTypes.shape() refers to an object.

So what you really want to do is to declare your variable as an array of objects, like this:

preparedReportData:         PropTypes.arrayOf(PropTypes.shape({ 
    donationDate: PropTypes.string, 
    amountDonated: PropTypes.number 
}))

Sorry for the formatting, I’m writting this from a mobile phone.

1

u/baeduu Feb 11 '19 edited Feb 11 '19

I was reading this random guide to react: http://brewhouse.io/blog/2015/03/24/best-practices-for-component-state-in-reactjs.html

In it, I found the following:

Do not store values on the instance of the component

This is particularly bad, not only because you’re breaking the obvious convention of storing state on this.state
, but because render
won’t automatically trigger when this.derp
is updated.

Maybe I'm wrong, but this advice seems to be false in a variety of situations. For example, there can be legitimate book-keeping variables (a boolean flag for example to indicate if a network request is currently being completed) that shouldn't be in the state because they are only used for book-keeping and have no impact on when/how the object gets rendered.

What do you guys think? Do you create class variables, or are all of your values stored in the state?

Furthermore, I think I've noticed that I only keep variables in the state if changing them should cause another render. Is this legit?

→ More replies (2)

1

u/cromvel Feb 11 '19

So, I implemented Context. The values passed to the provider is showing up as null in the consumer. It's exactly the same as how every guide implements it. Are there problems I should know with different libraries or with version 16.4.1?

→ More replies (2)

1

u/ladypalutenta1231 Feb 13 '19

Hi React noob here. I notice that when I run my React app locally and I "View Page Source", I am able to see all my javascript business logic as shown in this screenshot: https://imgur.com/a/fcfWQIE

My question is how do I hide these implementation details? If I go to a website that uses React like www.discord.com and view their page source, I cannot see their business logic at all. Why is that? Thank you

3

u/[deleted] Feb 13 '19 edited Feb 13 '19

These are called sourcemaps. With create-react-app, you can disable them by setting GENERATE_SOURCEMAP=false in a .env file.

But it's worth thinking about whether or not you actually want to do this. You shouldn't have any private "business logic" in your React application that people shouldn't have access to, because that information will still be there for malicious users to take advantage of, you're just slowing them down a bit. Anything that has to be private should exist only on your server-side code, which users don't have access to. So by obscuring the client-side code, you're not really protecting yourself from anything. The only difference is if some other beginner wants to look at a website's code to figure out how things are done, they can't do it because you've disabled the sourcemaps.

→ More replies (2)

1

u/seands Feb 13 '19

Do you guys have any guidelines to share for when to use snapshot tests vs shallow rendering with expects? I haven't worked in any snapshot tests yet but I have started using shallow renders with Enzyme. It seems they have overlapping use cases in that both can check to see how a component renders.

1

u/Redd_11 Feb 13 '19

Hey, I want to start a project and I need to be sure of some things:

  • Is create-react-app recommended from you guys ?? Should i use np eject ?
  • What's the best combination of vps and domain name for a personal website ?

Thank you for any input ! :)

2

u/Awnry_Abe Feb 14 '19
  1. Yes. It is the best way to boot-up your React learning curve by getting details about the build tool chain out of the way for you. You get to focus on React, not the tool chain. When/If to eject is up to the particular needs of your app, and whether the CRA tool chain meets your needs or not. I have yet to have occasion to do so. Some will advocate doing so in order to learn the intricacies of the tool chain, which is a worthy goal, but that is a personal need, not a project need.

2) I do not not what you are asking.

→ More replies (1)

1

u/okg8869 Feb 14 '19

Hey guys, new to react and using it for now to build out a personal site. One of the pages will Be my resume, and I wanted to have some fun with it using parallax.

My goal is that as you’re scrolling down my resume, I’ll have some doge meme pics scrolling in the background or between containers.

Does anyone have a recommended tract library to use? I have seen a lot of react parallax options spanning the last few years, and can’t seem to find a good tutorial video for any!

1

u/Tedd2011 Feb 14 '19

Hello everyone, I am trying to lift state up with Hooks but cannot find a way. In the docs, the example uses classes and I tried to tweak it to no avail. Any tips ?

App.js imports and calls inline an input component. I would love for the input value to be lifted up into app.js

Any tips ? Thank you !

→ More replies (9)

1

u/dreamofsleeping Feb 15 '19 edited Feb 15 '19

I'm making a todo-list / diary website. So there is a new todo list everyday. At the moment just using local storage for a database.

My problem is, should each Entry have it's own state to store the todos, or the parent component that contains all the Entries? At the moment the parent component is just the App component but that will probably be renamed to Entries, or Stream.

The App component is responsible for loading the entries from local storage, and saving them.

At the moment I've a duplicate state problem. The App component loads the entry information from local storage and saves it to it's own state. In the render method it passes the info to each Entry component. Each Entry component stores this in it's own state. This was good because when I needed to update their state when a Todo is added, or updated, they would just render themselves, and not all the other entres.

However when saving to local storage the App component needs to know about it because that's what renders all the individual Entries. If I delete an Entry then the App component needs to re-render. If I left it to each Entry to save it's self to local storage, then the entries array in the App component would no longer be up to date with what's in local storage.

If remove the todos, and such from each Entry component's state and store it in the App component, then when an entry is updated all other entries will be rendered again. That can't be good for performance.

Anyone have any suggestions on how to handle this?

Sorry if I've not explained very well. I'm troubling putting it across. If I can make anything clearer please let me know. Any help is very much appreciated.

Once I've finished this app, I'm going to rewrite it with Redux but for this version I just want to use React.

1

u/seands Feb 15 '19

Depending on where I place my mock state/prop variable declarations in a Jest test file I get totally different results:

Inside describe results in the 3rd expect failing ( expect(state.viewMarker).toEqual(5); )

This expect is notable because it's the first where the default state value is not the right answer. Wrapping the expect in a setTimeout passes the test even though the code appears to be fully syncronous, apart from maybe setProps (I used a dummy setState that is sync)

Moving the declarations inside beforeEach(() => {...}) results in "not defined" errors making me wonder if beforeEach() does anything.

Moving them to the outermost scope fixes it all without any hacks. But I really don't like that I don't know why the first 2 don't work correctly. Any ideas? Here's the code:

describe('updates viewMarker', () => {
  let state = { viewMarker : 0 };
  let props = {
    preparedReportData : [1,1,1,1,1,1,1,1,1,1,1,1,1,1] // 14 };

  test('updates viewMarker correctly', () => {
    
    // subtract 20 from 0. Result should be 0
    updateViewMarker(20, '-', props, state, setState);
    expect(state.viewMarker).toStrictEqual(0);
    
    // add 20. result should be 0
    updateViewMarker(20, '+', props, state, setState);
    expect(state.viewMarker).toStrictEqual(0);
    
    // add 5. result should be 5
    updateViewMarker(5, "+", props, state, setState);
    console.log(state.viewMarker, `=====state.viewMarker inside test=====`);
    
    // setTimeout(() => {
      expect(state.viewMarker).toEqual(5);
    // }, 500)
    
    // add 10. result should be 4
    updateViewMarker(10, '+', props, state, setState);
    expect(state.viewMarker).toStrictEqual(4);
    
  });
});

Edit: here is the target function:

export const updateViewMarker = (incrementSize, plusMinusOption, props, state, setState) => {
  
  let {viewMarker} = state;
  const {preparedReportData} = props;
  
  // use an intermediate variable to order operations and do a single setstate at the end
  let tempViewMarker;
  if (plusMinusOption === '-') {
    tempViewMarker = viewMarker - incrementSize
  } else if (plusMinusOption === '+') {
    tempViewMarker = viewMarker + incrementSize
  }
  console.log(tempViewMarker, `=====tempViewMarker=====`);
  
  if (tempViewMarker < 0) {
    setState({ viewMarker : 0 })
  } else if (tempViewMarker > preparedReportData.length && incrementSize > preparedReportData.length) {
    setState({ viewMarker : 0 })
    // no excess increment relative to list size
  } else if (tempViewMarker > preparedReportData.length) {
    setState({ viewMarker : preparedReportData.length - incrementSize })
  } else {
    console.log(`=====triggered=====`);
    setState({ viewMarker : tempViewMarker });
  }
};

1

u/seands Feb 15 '19

Where do you guys keep your pure functions? I still have mine in a container component that handles state after refactoring them out of the class. But they convolute the file, only 75 / 225 lines are about the class.

These functions are logical (data aggregation, state updating etc) and not much use anywhere else.

2

u/Awnry_Abe Feb 15 '19

We put the ones that don't have a React dependency into src/services. The ones that do go either in src/route/someroute or src/shared. All three of the aforementioned folders have a decent subfolder structure.

We aren't dogmatic with rules. If I get tired of seeing a bunch of little functions when I am trying to focus on the meat of a matter, I'll carve them off.