r/reactjs • • Apr 01 '20

Needs Help Beginner's Thread / Easy Questions (April 2020)

You can find previous threads in the wiki.

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. 🙂


🆘 Want Help with your Code? 🆘

  • Improve your chances by adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz.
    • Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
    • Formatting Code wiki shows how to format code in this thread.
  • Pay it forward! Answer questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.

New to React?

Check out the sub's sidebar!

🆓 Here are great, free resources! 🆓

Any ideas/suggestions to improve this thread - feel free to comment here!

Finally, thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!


34 Upvotes

523 comments sorted by

3

u/NeeHaow_World Apr 14 '20

Is it good practice to use styled components to replace css in react? It is harder to use styled components coz I don’t know how to style attribute and etc. Any other suggestions for css frameworks???

2

u/dance2die Apr 14 '20

You can apply styled components (SC) or other CSS-in-JS when you need it but not all the time but only situationally.

If you are having trouble with how to style attributes, understanding CSS would be the first step because CSS-in-JS would require you to understand CSS first.

Brent Jackson (a dev behind styled-system & Theme-UI) has an article discussing what CSS-in-JS is and what not.

3

u/silverdished Apr 20 '20

What is Gatsby? What can it be used for? What are its powers and limitations?

1

u/dance2die Apr 20 '20 edited Apr 20 '20

Mostly known as a static site generator but you can also create dynamic sites.

You can prebuild content from server-side during "build" time and thus can reduce the JavaScript loading time on client-side.

What can it be used for?

You can refer to their Show Case page (lotcha cool sites and usages).

What are its powers and limitations?

Gatsby builds markups during build-phase so if your data source value changes, you need to re-build (unless you are taking a SPA (Client-side rendering) approach).

You can refer to this article for more technical issues.
https://developers.google.com/web/updates/2019/02/rendering-on-the-web
(Check out the "Wrapping Up" section at the bottom first. It's got a nice overview and a kick ass analysis image).

2

u/cmaronchick Apr 14 '20

I just built an app using Material UI, and for my next app, was going to try something different and tried to go with Semantic UI.

What I like about Material UI is the easy theming capabilities (primary color, secondary color, etc). I didn't see any easy way to do that with Semantic UI while also using webpack. I found some docs for how to do it, and ultimately I banged my head against the wall for about 4 hours before finally giving up.

Is there anyone who'd like to share their repo that successfully created a custom Semantic UI theme while also using webpack? Thanks.

1

u/dance2die Apr 16 '20

Looks like Semantic isn't maintained, thus might want to check out the community fork, Fomatic UI.

I am sorry but I couldn't find any info nor a community...

Would you mind asking StackOverflow? (https://stackoverflow.com/questions/tagged/fomantic-ui)
Please follow https://stackoverflow.com/help/how-to-ask (posting what you tried and what didn't work).

2

u/tall_and_funny Apr 16 '20

I have completed the react course on freecodecamp - the one with builtin ide, it then jumps right into redux, I think there must be a couple topics not touched yet, but maybe they don't come under react? Like react router? What other main topics I might be missing out on? How to I close this gap?

2

u/dance2die Apr 16 '20 edited Apr 16 '20

Hi u/tall_and_funny.

FreeCodeCamp (https://www.freecodecamp.org/learn/) has Redux as its own section and Redux is framework/library agnostic. Meaning, it can be used with React, Vue, Svelte, etc.

The next section React-Redux should show you how to "connect" Redux with React (using React Redux).

React router isn't a prerequisite and you can safely move onto the Redux section.

2

u/tall_and_funny Apr 16 '20

Oh thanks for clearing that up. I'm new to this sub and I've actually learnt a lot just browsing here.

2

u/dance2die Apr 16 '20

You're welcome & enjoy React~

2

u/[deleted] Apr 19 '20

please tell me in simple words, what is difference between history.push("/") and <Redirect to="/" />

3

u/dance2die Apr 20 '20

The former history.push(...) is an imperative method, while the latter is declarative.

Meaning, history.push would be used to manually redirect a user to a different location while <Redirect /> is used as part of a component's returned element.

→ More replies (1)

2

u/[deleted] Apr 21 '20

Hey, I'm trying to import a component from this pluggable Trello-Like component into a page on my application. https://rcdexta.com/react-trello/?selectedKind=Custom%20Components&selectedStory=NewLaneForm&full=0&addons=0&stories=1&panelRight=0

I can't figure out how to plug this specific component into my application. Here is the code. Would I just download it and put it into my components folder and add it into my page like <NewLaneForm />

https://github.com/rcdexta/react-trello/blob/master/src/components/NewLaneForm.js

2

u/dance2die Apr 21 '20

The project source's README shows how to install it (via NPM/yarn) and import it in your code.
Found it hard to follow as their home page is a storybook w/o any documentation.

https://github.com/rcdexta/react-trello#getting-started

2

u/badboyzpwns Apr 23 '20

with redux, is it bad practice to pass props to a component (since ieverythings handleed by action creators and reducers) ? eg <Component prop="hi"/> is bad!

→ More replies (6)

2

u/HopefulSlice0 Apr 01 '20

How does

import React from 'react';

work?

...when you're using functional components and not actually calling React.Component?

(or better yet, why does it not work when you remove it?)

Does this have to do with babel?

Where's the actual logic that ties a random function to a React? What concept am I missing?

5

u/cmdq Apr 01 '20 edited Apr 01 '20

I think what you're seeing is indeed related to babel, but in a roundabout way.

We'll start with JSX. JSX, as you may know, is not valid JavaScript syntax, so it needs to be transpiled. Check out this link to the babel repl.

You can see that the JSX on the left side got transpiled and is shown on the right side. Curiously, It's trying to call React.createElement, although so far, this is just some JSX with no React involved. What's going on?

This is due to the history of JSX. When it was introduced, there was only one entity using it—React! So the React.createElement was used as the default method to turn the transpiled JSX output from the plain description format of a DOM structure into actual elements.

By the way, you're not limited to using React.createElement. In fact, some libraries need the developer to change the default method which interprets the transpiled JSX. This is done via a "pragma", a special comment at the top of the file which tells babel to use a method you provide. Check it out, here we set it to console.log.

Now, what does this have to do with your question? I assume that when you removed the React import, but still tried to use JSX somewhere in your code, you saw a React is not defined error which happens because the default JSX handler is trying to call React.createElement, but React is not defined.

As for your questions regarding React.Component (which I'll call class components) and function components—React initially started with only class components. Because of reasons, they needed to use inheritance to extend a plain class with some necessary under-the-hood changes so that React could accept a Class as a component.

Function components came a bit later, and did not have the same restrictions as class components! You're now able to just hand React a function, and you're off to the races.

In the end, there's no special magic that ties a function to React. React just looks at the thing you're telling it to render, checks whether its type is a function, and will then call that function for you with its props. (As always, there's some more stuff happening under the hood, but that's the gist of it)

Phew! As I said, this was a bit roundabout. But I believe that it's important to know the history of some of the decisions that were made to understand why we're doing some things a certain way :)

Hope this helped! Let me know if you have any more questions.

Here's a really good post on pragmas from the Gatsby folks: https://www.gatsbyjs.org/blog/2019-08-02-what-is-jsx-pragma/

2

u/dance2die Apr 01 '20

Wow. Nice explanation and the helpful link :)

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

1

u/embar5 Apr 01 '20

Can you guys give an example of when you would write a closure? I know they return a function that has access to private state. I don't know a common pattern to use them on.

2

u/dance2die Apr 03 '20

You'd use closure for cleaning up in useEffect.

  useEffect(() => {
    const id = setInterval(() => {}, 3000);
    return () => clearInterval(id);
  }, []);

In the code above, id is closed over to the next render, thus able to stop the interval by the correct id.

3

u/Awnry_Abe Apr 02 '20

onClick handlers for list items. If I'm iterating over an array of items, my click handler will look like:

const handleClick = (item) => (event) => {
  ....code that uses item.
}

In render return:

{ items.map(item => (<button onClick={handleClick(item)}>...etc

1

u/andrew009 Apr 02 '20

withRouter or useHistory with react-router-dom v5? both are doing the same thing from end user point of view, but since I like functional approach more, I'm favoring the latter. Is there any reason for me to go with the former?

2

u/dance2die Apr 03 '20

If you happened to need to keep the component either pure, or make it re-usable (meaning, not dependant on React Router), then you'd use withRouter on the component.

→ More replies (1)

1

u/IdleScV Apr 03 '20

do people still use Fragment?

5

u/dance2die Apr 03 '20

Yes. It's still used.

The reason you might not notice is that people tend to use the empty element tags, <> </> instead of <Fragment></Fragment>.

→ More replies (2)

1

u/molusk1337 Apr 04 '20

Any good tutorials how to make multi-items slider or any easy to implement frameworks for that? Trying to make “Our courses” content as a slider. Thanks

2

u/dance2die Apr 06 '20

A quick googling shows this one.
https://www.youtube.com/watch?v=3ax9TW2c2bY

Just skimmed thru and so long as you understand the concept, you can build one yourself.

I haven't used a carousel so not sure which one to recommend. Lotcha result.

→ More replies (2)

1

u/MeltingDog Apr 07 '20

Does anyone know how I "query" a JSON file? Anyone know of a tutorial?

1

u/dance2die Apr 07 '20

If you mean "query" as in an SQL query, there isn't one.
You can check out json-query or use MongoDB, which stores documents in JSON format (and you "query" it using javascript).

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

1

u/Ali-Zuhair Apr 10 '20

Hi,

I am fairly new to React Native, so there are still some things that I don't know how to do.

So can some one help me with this question:

What is the correct way to handle HTTP response in React Native component

1

u/dance2die Apr 11 '20

It looks like it's answered &
for those interested in the answer, 👇 https://stackoverflow.com/a/61149638/4035

1

u/Tsunami874 Apr 10 '20

Hi,

I have an issue with useState, I'm fetching data from an api and trying to display it, but it seems that my setData function triggers a re-render which restarts the api fetch which re triggers a re-render etc

export const Sorter = () => {
    const initialData = [
        {uv: 1},
        {uv: 2},
        {uv: 3}
    ];

    const [data, setData] = useState(initialData);
    getRandomlySortedNumbers(100).then(numbers => {
        const newData: any = [];

        numbers.data.map((entry: number) => newData.push({uv: entry}));
        setData(newData);
    });
    return (
        <>
            <BarChart width={1800} height={1000} data={data}>
                <Tooltip/>
                <Bar dataKey="uv" fill="#fff"/>

            </BarChart>
        </>
    );
};

1

u/dance2die Apr 10 '20

While Sorter is instantiated, getRandomlySortedNumbers is called. Then the element is rendered (via return), and setData is called, which trigger the re-render.

At this point, getRandomlySortedNumbers is called again, causing the re-render, over and over.

getRandomlySortedNumbers is a side effect, and thus need to be wrapped in useEffect.

2

u/Tsunami874 Apr 10 '20

I did this and it works, thank you very much!

    useEffect(() => {
        getRandomlySortedNumbers(100).then(numbers => {
            const newData: any = [];

            numbers.data.map((entry: number) => newData.push({uv: entry}));
            setData(newData);
        });
    },[]);
→ More replies (1)

1

u/badboyzpwns Apr 14 '20

in redux, should action components be defined with arrow functions or functions hi(){}?

2

u/dance2die Apr 14 '20

Irrelevant and be aware that arrow functions aren't hoisted.

→ More replies (2)

1

u/i-code-stuff Apr 16 '20

What are some of the good to automate deployment?

For example, if you're working on a Firebase site, you can deploy with a single command. Assuming I've got a cloud server, what can I set up there to deploy to it quickly?

2

u/dance2die Apr 16 '20

It depends on what and how you want to deploy.

Frontend projects can be committed to Github/Gitlab repository & automatically be deployed.
You can also set up a GitHub action or a CI/CD (continuous integration/deployment) pipeline using CircleCI, Jenkins etc to deploy after running tasks such as testing.

From your point of view, such a setup helps you just commit & push to your repository.

2

u/cmdq Apr 16 '20

I've used Dokku with a lot of success, but I haven't set it up myself, so I can't speak to the ease of it. Using it was pretty solid and convenient though!

If you're looking for completely managed solutions, netlify and zeit both have very generous free plans and work well.

1

u/dance2die Apr 16 '20

Woot woot. I wanted to try it out on a Digital Ocean droplet. How/where do you host Dokku instance?

2

u/cmdq Apr 16 '20

Seems like DO offers an official image for dokku: http://dokku.viewdocs.io/dokku/getting-started/install/digitalocean/

Edit: I think back then we used it on railslabs or something? Been a while :D

→ More replies (1)

1

u/CYMAD Apr 21 '20 edited Apr 21 '20

Hello, I started learning react and was building my first simple app but there is a single issue that i want to ask. I'm trying to fetch data from weather api with axios. my first request is always giving errors(400 bad request) but other ones are ok and can work with data.im sharing codes https://imgur.com/a/ikeNjGp

3

u/dance2die Apr 21 '20

this.setState is an asynchronous method. Meaning, when you do this.setState({q: city}) and try to access this.state.city, it might not be defined/null.

You might want to pass city directly to the api call weather.get(...).

Or you can use a callback to ensure that the state value is set and call the API within the callback (not recommended unless specific reason to do so as you already have an access to city value).
https://reactjs.org/docs/react-component.html#setstate

2

u/d4vsanchez Apr 09 '20 edited Apr 10 '20

Hello everyone, I'm reading some code in GitHub and found out the following useEffect implementation:

React.useEffect(() => {
  if (!enabled) return;

  window.addEventListener("scroll", onScroll);
  onScroll();

  return () => {
    window.removeEventListener("scroll", onScroll);
  };
});

As I've read the code and its basically a custom implementation that does what IntersectionObserver does, so far so good. My question is more about how is this useEffect implemented without dependencies; I'd have implemented it with at least an empty array as its dependencies so it gets ran just one time and the return expression gets called before the component is unmounted.

Is there any benefit of creating this useEffect without the dependencies and making it create/remove the event listener basically on every re-render?

3

u/Nathanfenner Apr 10 '20

Since no dependencies are passed, it will run again after every render. This means that the correct (i.e. current/new) scroll closure will always be captured and executed, and it will (correctly) stop immediately once it rendered with enabled == false.

The only downside to this is that if it re-renders a lot, it will redundant add/remove similar event listeners. Unless it's re-rendering every frame, this is unlikely to actually cause any noticeable problems, though.

1

u/jkettmann Apr 10 '20 edited Apr 11 '20

I think you found a bug :-) If the author used ESLint it would tell them that the useEffect doesn't have any effect. You could just remove the useEffect and run the function directly inside the component.

Edit: I guess I was a bit quick here. It's probably not a bug since it should work. Also as /u/franciscopresencia mentioned the useEffect is important here to remove the listener. Still I think there should be a dependencies array containing enabled and onScroll

3

u/franciscopresencia Apr 11 '20

This is not true; the window.removeEventListener("scroll", onScroll); would not happen if it's run straight inside the component, thus leading to an unbounded number of new listeners. This would at best result in a memory leak, at worst it'd break because `onScroll` is called too many times.

2

u/jkettmann Apr 11 '20

You're right, I didn't think of the cleanup. So you can't just replace it by a function. Sorry for being misleading.

Still this looks very much like it should have a dependencies array

→ More replies (2)

1

u/latitudehopper Apr 12 '20

Ok. This is a dumb one. I've been playing with usecontext and usereducer. Is it possible to have a global state that when changed automatically rerenders across the app on different tabs? For example, pushing items to an array in the global context and it re rendering a list in several places?

3

u/cmdq Apr 12 '20

Seems like it's possible! And of course there's a hook for it: https://github.com/gus3inov/use-share-state The keyword Broadcast Channel was crucial in finding this :)

1

u/dance2die Apr 12 '20

Thank you for the keyword! I didn't know what I didn't even know either :)

→ More replies (1)

1

u/pruggirello Apr 20 '20

Hey everyone!

I'm a little confused on how React Router works, mainly how to implement it in my app. I have a toolbar on the top of my webpage and I was able to implement the Link components just fine. My problem is navigating my pages using Router and the toolbar component. Initially, I was using buttons, a switch statement, and setState to change which page renders. Now that I have the Links rendering, I'm wondering how to implement the Router in the webpage. Is anyone willing to point me in the right direction?

Also, something weird is happening with my css for the Links. The colors change appropriately, but my transformY doesn't occur. This worked on my old toolbar component, but when I redesigned it, it stopped working. It's not an issue, it's just weird.

Thanks!

4

u/[deleted] Apr 20 '20

First things first, if you want to use react-router you need some foundation about react-router-dom elements, here's the basics you need to know.

BrowserRouter

It's the top level container that enables you to use routing inside child components, you wrap your app/component with it like this.

<BrowserRouter>
<App />
</BrowserRouter>

There's also a baseName which an extra optional prop you might need if you don't serve your react app from the a base domain, say mydomain.com/app for example, then you'll need this to be specified to '/app', and that's it. Now we're ready to 'routify' the app.

Route

Say you need to render different components for different urls, for example. Say you have a component called Home and you want to render this component at /home from your base url, remember the base url, this route is appended to it.

<Route path='/home' component={Home} />

Another way around you can specify a function that returns JSX as a prop, this is done by the render prop.

<Route path='home' render={() => <h1>Hello from home!</h1>} />

There's also the exact boolean prop, which specifies that we want to render this only at this exact path and nothing else that contains it. For most cases you'll need only these props, but there's some few to look at in the docs.

Link and NavLink

Suppose we have our App component to render this JSX.

<div>
<Route path='/home' component={Home} />
<Route path='/profile' component={Profile} />
</div>

Inside the Home component we can implement routing by using either Link or NavLink component.

They're basically the same, with the added functionality of styling provided by the NavLink, which makes it ideal for navigation component in the header which contains your different routes.

Both have to prop, which as the name suggests, routes you to the specified route.

<Link to='/home' />
<Link to='/profile' />

Both renders to an a tag but handled with the react router, so you can pass any prop that applies to an a element.

NavLink provides activeClassName and activeStyle which helps in styling this a element when the route is present, also exact prop returns back with similar functionality, it specifies that active styles or classes are applied at this specific route only and not to its extended routes.

From here we can go in some detail.

Redirect

This element doesn't render any JSX, otherwise when it's rendered it provides a declarative way of redirecting to specific routes. for example in the render function we want to redirect to the login page if not logged in.

if (!loggedIn) {
return <Redirect to='/login' />
}

Switch

This is one useful component, it simply says acts like the good old switch statement, and renders only one route of its children.

<Switch>
<Route path='/profile' component={Profile} />
<Route path='/dashboard' component={Dashboard} />
<Route path='/' component={Home} />
</Switch>

What you think it will render from this at /profile? It's easy it renders the Profile component, so where's the trick? Let's we change the order.

<Switch>
<Route path='/' component={Home} />
<Route path='/dashboard' component={Dashboard} />
<Route path='/profile' component={Profile} />
</Switch>

At the '/profile' we have to possible solutions, '/profile' path obviously and '/' as '/profile' begins with '/'. so it might render both. But remember all routes are in a Switch component, which means it will only render one route, and the first one that fits is '/' and renders Home component.

This is basically react router dom elements in a nutshell. There's a lot you can learn about react router and react router dom, the docs at react training are very good, also I'm here to help to clarify.

2

u/dance2die Apr 20 '20

Nice explanation~ Thanks for sharing

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

1

u/xSnag Apr 21 '20

Hey, i am having trouble uploading my react project to github. I am trying to use it for my main domain on github, not an repo. like my <user>.github.io, domain. I am using router, not sure if that has an affect on it, but it is only displaying the readme on my site, but when I uploaded a repo using react it uploaded with no problem. Here is a picture showing what I am getting when I try to upload my portfolio website, vs when I just make a repo https://imgur.com/a/fJp0tdq

2

u/cmdq Apr 21 '20 edited Apr 21 '20

Make sure you're pushing your build artifacts to the gh-pages branch, not master. See here: https://gist.github.com/chrisjacob/1086274/382ef1ccc22b57b9b1f0e3a362b39e806b9ba04c

1

u/dance2die Apr 21 '20

*gh-pages

2

u/cmdq Apr 21 '20

Woops, thank you ;)

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

2

u/IanAbsentia Apr 01 '20

It's the React development team's official recommendation to define a function invoked within the `useEffect` hook within the hook itself if the intent is to avoid the exhaustive-dependencies error.

https://reactjs.org/docs/hooks-faq.html

Search for: "The recommended fix is to move that function inside of your effect. That makes it easy to see which props or state your effect uses, and to ensure they’re all declared:"

What I'm wondering is whether that function will be defined again and again every time the hook is run and whether, as a consequence of this, there could be performance issues.

5

u/[deleted] Apr 02 '20

whether that function will be defined again and again every time the hook is run

Yes.

as a consequence of this, there could be performance issues.

No. Defining a function is trivial.

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

2

u/deep-data-diver Apr 03 '20

Could someone help me understand hooks and the difference between class components and functional components and their use?

6

u/[deleted] Apr 03 '20

Same use, function components are newer and class components are being phased out. Use function components unless working on legacy projects.

Hooks let you store state related to a component, and they let you respond to changes in the component's lifecycle: when props or data changes. Such as setting event listeners, timers, fetching data, etc.

Anything more detailed and I would be duplicating the official React docs on hooks, so just go read those. They're very good.

2

u/andrew009 Apr 03 '20

Is there any community-approved approach to protect login/register views from already logged in users? I've done something like this with useEffect, but what I don't like is that if user is logged in and clicks on login button, he/she still can see login form for a very short period of time; I would like to eliminate it completely. Snippet from my code: useEffect(() => { if (isAuthenticated) history.push("/dashboard"); }, []);

4

u/Awnry_Abe Apr 04 '20

useEffect is 1 cycle behind what you need. You have the right logic, just in the wrong place. The typical way is via conditional rendering of the Login component--dont render it at all (or have it return null) if the user is authenticated.

→ More replies (1)

2

u/Jaydara Apr 04 '20

Hello! I am trying to make a small, simple react app which has the following functionality: 3 drop-down menus with different (integer) values as options, and a button, which on click prints the sum of the selected values of the 3 drop-downs. I managed to make the drop-downs and the button visible correctly, the drop-downs can be clicked and the value can be changed within it.

However, the button right now does nothing, because I have 2 large issues:

  1. Cannot somehow add an onClick functionality to the button, it just doesn't seem to do anything right now, I tried to make it print "Sum Should be here" for now, but it doesn't. I tried to add an onClick and call a function for it, but it doesn't seem to execute the function. Details in code.
  2. I cannot access the values of the drop-downs. I have difficulty following ready examples because those I found only have 1 drop-down, and I don't know how I differentiate between the 3. So I basically need something like a function that returns the value of the desired drop-down that the user has selected on the moment the function is called. I tried using alert(red.value) style solution (where red is the selection id) but it said red was undefined.

Here is my current code: https://pastebin.com/zSiArj23

3

u/Awnry_Abe Apr 04 '20 edited Apr 04 '20

In react, you don't print things (ie return markup) in event handlers. All creation of html is done in the return of the render() function for a class component or the return of functional component. What is generally done in event handlers instead is setting state. Two ways to go about it come to mind.

  1. each drop-down has corresponding state, and the state value is set in onChange handler. The onClick handler of the button would access that state, tally it, and set a 4th piece of state called 'total'.
  2. use the ref property of each drop down. You would still be making 3 instances of something--refs instead of state. The onClick of the button would access the 3 refs and dereference their value.

There is a section in the react docs titled "Thinking in React". That would be a good place to start as it addresses the common misunderstanding that you have.

→ More replies (2)

2

u/Wraith000 Apr 04 '20 edited Apr 04 '20

I'm using sessionstorage to persist state for an E-com project, things like cart, checkout etc

How can i prevent a user from messing with stuff in the sessionstorage, or is there a better way to persist user state ?

Also I've been using the Context API and just got into Hooks when I had some trouble with context / lifecycle stuff.

3

u/Awnry_Abe Apr 04 '20

Let them fiddle. Your backend needs to guard against such hackery.

2

u/achunkypid Apr 04 '20

Hello, this might be a confusing question but I'm building a productivity app here

https://ivanlancedeleon.github.io/productivity-app/

and what I want to do is to make it so when you click a date on the calendar, it can pop up where you can write events and what not to it. I'm using React-Calendar but I'm still very new so I'm not quite sure how I'm supposed to go about this ? I'm thinking now i should make two components into one component for the calendar section so I can share the state data between the two but I'm not quite sure.

2

u/aidang95 Apr 06 '20

Brand new to react, found a nice little tutorial about making a journal in react which I have working.

How do I go about adding a new page to my app? I want a little menu where I can switch between pages but I am getting a little confused looking online (routers etc?)

Also again im not sure how complex my second question is has like i say im new to react, however when I input an entry into the journal, it only stays until the page is refreshed then everything dissapears, how can I make sure these stay until the user deletes them? Is there Local Storage or anything I can use?

→ More replies (1)

2

u/fa1re Apr 07 '20

So I would like my svg image to be responsive. Inserting "vw" units directly into the width and height of the svg doesn't work in Firefox (see http://lore-hunters.herokuapp.com/). It seems that I should embed the svg element inside an image element (<img src={svg} />) - however the code doesn't work:

export const AdventurerToken = (props) => {
    const color = props.color;
    const adventurerSVG =
        <svg width="100" height="100" viewBox="0 0 99 119">
            <metadata>
                Created by potrace 1.15, written by Peter Selinger 2001-2017
            </metadata>
            <g transform="translate(0.000000,119.000000) scale(0.100000,-0.100000)" fill={color} stroke="none">
                <path d="M336 1174 c-10 -9 -16 -33 -16 -62 0 -26 -4 -52 -8 -59 -4 -6 -35 -17 -69 -23 -35 -7 -68 -19 -74 -26 -23 -28 50 -108 134 -145 20 -9 27 -19 27
-40 0 -23 -5 -30 -27 -35 -98 -21 -212 -74 -265 -122 -36 -32 -38 -38 -38 -92 0 -84 11 -92 134 -105 32 -3 62 -8 67 -11 11 -6 -12 -69 -50 -133 -77 -129
-114 -215 -115 -266 l-1 -50 168 -3 168 -2 57 90 c33 52 63 89 71 88 8 -2 35 -41 61 -88 l47 -85 172 -3 171 -2 0 43 c0 56 -35 151 -90 247 -86 149 -86 148
-74 160 6 6 43 14 83 17 98 8 121 26 121 97 0 62 -17 89 -84 133 -42 28 -157 74 -221 88 -29 6 -28 7 23 24 79 27 122 76 122 139 0 47 -72 102 -135 102 -18
0 -25 7 -30 33 -3 17 -13 49 -22 70 l-16 37 -138 0 c-112 0 -141 -3 -153 -16z"/>
            </g>
        </svg>

    return (
        <img style={{width: "10vw"}} src={adventurerSVG}/>
    )
};

What am I doing wrong?

→ More replies (3)

2

u/Chr0noN Apr 07 '20

Is it possible to disable the animation of the draggable item going back in react-dnd ?

→ More replies (1)

2

u/embar5 Apr 07 '20

Has anyone created a guided tour of a login area? Any specific tooling you would use?

I think it may be able to be done the following way

  1. Popovers (in Material UI) give notifications of features
  2. Clicking the "Next" button on a popover will change various states to show new sections or activate new features
  3. At the end, another state variable like guidedTour is set to false so the tour option is no longer presented. This will also happen if they select an option to skip the tour.

The main trouble with this would be clearing the state, since everything was changed through an unusual path. I think it will be okay though, as it is step by step and so the logic of clearing a previous state before altering the next one shouldn't be too bad.

→ More replies (3)

2

u/maostah Apr 07 '20

Hello. Please help with suggestions. I would like to create a PWA where user can update their activity. The activity that the user log is for their own viewing, like financial app. What options do I have for local database? Is local storage the only option? The data is supposed to be in boolean form. So I guess the size of the database should be small. I'm not entirely sure on this.

Thank you in advance :)

→ More replies (2)

2

u/[deleted] Apr 07 '20

Hello!

Is it okay to use css in js files in React? I mean it seems kinda strange for me. I don't want to use it, LOL. Are there many vacancies that require such skill?

→ More replies (1)

2

u/badboyzpwns Apr 11 '20

newbie clarificaiotn; from what I understanding, binding this/using arrow functions are only important for callback functions.

So! this is completely valid, correct? (Sorry, I don't have react set up right now! )

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.hi = 'hi'
  }
  
  
  testMe(){
    console.log(this.hi); //the "this" would be still be binded because it's not a callback
 }

  render() {
    return <button onClick={this.clickHandler}>Click Me</button>
  }

  componentDidMount(){
       testme();
  }
}
→ More replies (1)

2

u/pruggirello Apr 12 '20

How do I make a new paragraph or line break? I've tried <br>, that doesn't work. I've tried \n, that doesn't work. How do I get a new paragraph in my string?

→ More replies (7)

2

u/molusk1337 Apr 12 '20

I'm building a language course website which has "card" component rendering different information with a map function. Now I have "Read more" button on each card and once clicked I would like it to redirect to a differenet page and show content depending on the course. This new page would look the same on every component but the information would be different. How can I achieve this in Reactjs ? What is it called and maybe someone has good information on that? Thanks!

3

u/cmdq Apr 12 '20

Since you mention redirecting to a new page, I assume you're interested in having some kind of routing via URLs. react-router is a popular option to do this sort of thing, do check out their many examples.

After you did that:

  • You'll likely want to set up some kind of routing for your app with two routes, one card listing, one card detail, which would probably take a url param to identify a card. In expressjs notation: /cards and /cards/:cardId
  • the 'Read more' button would be a Link component, linking to /card/:cardId

Let me know if you get stuck!

→ More replies (6)

2

u/Chr0noN Apr 13 '20

How do I manage my yarn.lock file? Today one of the packages got updated which was the dependency for a library that I was using and completely broke me react project. I had to manually edit the yarn.lock file which according to Yarn is a big no no. React libraries have so many dependencies, so how do I prevent this from happening again ?

3

u/cmdq Apr 13 '20

Short version:

You could probably fix this by removing the ^ symbol in front of your packages' version number in package.json and run yarn install again.


Full version:

Hey, the *.lock files are generated from the version range information in package.json, so as you already said, you should not edit them directly.

Instead, check the entry for your package in package.json's dependencies or devDependencies.

It probably looks something like this "your-problematic-package": "^1.0.0".

You might be wondering about the ^ character (circumflex)! NPM follows a standard called semver which not only defines certain patterns for version numbers, but also ways to target a range of versions. The circumflex in this case means

include everything greater than a particular version in the same major range

So, assuming you had a circumflex in front of your version (which is the default range NPM chooses if you don't explicitly set one while installing), this would match any version in the 1. major range. Another way to write this would be 1.x or even 1.*.

In your case, the package maintainer of your-problematic-package might have inadvertently introduced some kind of breaking change which got automatically installed when you last executed the yarn install or (maybe) yarn add command (not sure about this one).


Here's a primer on semver: https://nodesource.com/blog/semver-a-primer/

And here's a semver range playground:https://semver.npmjs.com/

→ More replies (4)

2

u/embar5 Apr 14 '20

Are class components obsolete now? If not when would you guys still use them?

4

u/cmdq Apr 14 '20

class components have some features left function components can't do (see ErrorBoundaries), but that too might be moved to hooks at some point.

If you're just starting out now, stick to function components unless you have a good reason to use a class component.

2

u/Chr0noN Apr 16 '20

How do I export the contents of a div or component to a png in React ?

→ More replies (5)

2

u/embar5 Apr 23 '20

I'm looking to add a contact form to a static site. I notice now it's not so easy to copy/paste contact form code when the site is in react.js, different levels of abstraction I guess.

How are you guys handling this? I'm guessing you write the form code yourself and then send the request to a mailing service's API?

3

u/vijit-ail Apr 23 '20

Correct. But usually, you don't access any external service directly from your frontend, as most of these services require an API key. So you probably need to proxy the request via your backend.
There's this service called Formspree that does not require any API key and you can directly use it in your frontend.

→ More replies (1)

2

u/YakiHon Apr 27 '20

I have a problem re-rendering an array of objects similar to this:

data[{
    name: "name",
    amount: value,
...
},{
    name: "name",
    amount: value,
...
}...

You guess the general idea. I then have + - buttons to change the amount and if it reaches 0, it is erased from the data. I also have a field to input new named data.

The "remove" and "new entry" instances do trigger a re-render, but just changing the amount does not (despite the values changing) until it reaches 0.

the onClick triggers a function like this:

const onChangeAmount = (key, type) => {
  let copiedData = data;
  if (type.math === "increase") {
    copiedData[key].amount++;
  } else {
    if (copiedData[key].amount === 1) {
        //removes the entry
        copiedData = copiedData.filter((id) => {
        return id.name !== copiedData[key].name;
      });
    } else copiedData[key].amount--;
  }
  setDisplayedDeck(copiedData);
};

What should I change to have it always rerender?
Is it correct to use a "copiedData" value or can I work with the main value? (using hooks obviously).

I have tried a lot of stuff and at this point I am quite stuck on this... Tahnk you!

4

u/cmdq Apr 27 '20

let copiedData = data; does not copy your data.

Therefore, while you mutate the state data directly, react will not recognize your data as a different from the previous data, and won't update the state.

This is likely just a performance optimization on their part, but it should also tell you that you can't directly mutate state and expect it to work. Now, the other branch creates a new array because you call .filter which always returns a new array.

Check out this codepen: https://codesandbox.io/s/4mbqp and swap around the two let copiedData lines to see how the behavior changes.

Note: I use spread syntax to create a copy of the old state const newArray = [ ...oldArray ], which could also have been done like this const newArray = oldArray.slice() which also returns a copy.

4

u/YakiHon Apr 27 '20

Thank you very much! This works great in my application too :)

I'm quite new to javascript, but spread syntax is fine. I use it in many other places but did not think this could be the issue here!

Just so I understand it clearly... the idea behind

let copiedData = [...data]

is correct. You do want to create a copy to mutate it instead of directly mutating the main value every time, right?

→ More replies (1)

2

u/imaneuralnet Apr 28 '20

This is perhaps a better question for r/gatsbyjs, but it appears you have to get permission to post there.

I have some HTML generated from an outside source that contains LaTeX equations. Is there a way to use the gatsby-remark-katex plugin on HTML that hasn't been generated by gatsby-transformer-remark?

3

u/cmdq Apr 28 '20

Check out https://github.com/remarkjs/remark-math/tree/master/packages/rehype-katex. If that doesn't fit the bill, there's a whole universe of packages for this kind of stuff: https://unifiedjs.com/

2

u/badboyzpwns Apr 28 '20 edited Apr 28 '20

when you do "create-react-app" I've read that it automatically installs an ESLint. I don't see it warning me in the text editor (VsCode) though, is that normal?

For example, I wrote this and it's not giving me a warning.

import React from 'react';

const StreamList = () =>{
    return <div>StreamList</div>
}
export default StreamList;
wewew

and

const StreamList = () =>{
    return <div onClick=poop()>StreamList</div> 
    //dosen't warn me that poop was never created
}
export default StreamList;

2

u/[deleted] Apr 28 '20

CRA includes a configuration for eslint, and installs the eslint package which is used by the build process. You still need a vscode extension for eslint if you want vscode to understand it.

→ More replies (1)

2

u/GhostofBlackSanta Apr 28 '20

Hi, I am a junior dev with backend experience in C++ and a Python. I've done absolutely nothing in frontend and don't know JavaScript but I am very interested in learning React. I was recommended Tyler McGinnis's React class was the way to go from this subreddit and I am halfway done with it but I don't feel like I understand any of it and its probably because I don't understand the JavaScript syntax yet. Does anyone know the best way a beginner can learn these two topics?

2

u/[deleted] Apr 29 '20

In Python You use classes and OOPS. so everything is connected. the main difference between javascript and python or c++ is. javascript is functional which means everything should be treated as a method even so so-called classes in javascript are functions.

javascript function/methods only do one thing.

const sum = (a,b) => a + b

This above function. takes two numbers a and b and adds and returns the result.

that is all you need to know about javascript. functions only do one thing.

The main difference between react and python is. in py,then we think of a way to connect classes and methods. in react. every component is simply a function or a method that does one thing and only one thing. it gets its props (arguments)

let's say you wanna create react application that does arithmetics.

//components that adds

export default function adder(props) => props.a + props.b

//component that substracts.

export default function substractor(props) => props.a - props.b

//components that multiplies.

export default function multiplier(props) => props.a * props.b

//component that divides

export function default divider(props) => props.a / props.b

//components that Calls

export default function arithmetic(props) => if (props.substract === true) {

return <substractor a = {props.a} b = {props.b} />

}

see everything is thought of as a function.

1

u/linuxmintquestions Apr 01 '20

Getting to grips with useReducer. The standard dispatch syntax uses an action type/payload object often processed in a reducer switch statement. Why don't we use direct function calls?

Why do we use this syntax:

dispatch({'type' : doThing , 'payload' : data})

Instead of something like this:

dispatch.doThing(data);

2

u/cmdq Apr 01 '20

There are certainly libraries/approaches that would give you something like a direct function call. Zustand for instance is a personal favorite, but there are probably hundreds of slightly different approaches out there :)

useReducer though, subscribes to the idea that state should not be changed directly, but the change should be described by an action, which then gets interpreted by a reducer which finally changes the state. The idea is to have a clear, formal description of changes which can be traced, or saved for und-redo, etc.

Redux is a popular library that does exactly that, you might have heard of it :)

1

u/linuxmintquestions Apr 01 '20 edited Apr 01 '20

Ok, thanks. Do you see any downsides to this approach? (EDITED)

export default function (initialState) {
    const [state, setState] = useState(initialState);
    const actions = {
        doSomething : (payload) => setState(payload),
        doSomethingElse : (payload) => setState(state + payload)
    }
    return [state, actions];
}

Then in the component

import useCustomHook from './useCustomHook';

export default function () {
    const [state, dispatch] = useCustomHook();
    return (    
        <button onClick={dispatch.doSomething('somePayload')}>{state}</button>
    )
}

It just seems counter intuitive to me to have state change calls not bound to any particular state/store. Would this method not be able to implement the same save/undo/redo features you described?

2

u/dance2die Apr 01 '20

Each one of useCustomHook() will give you a different state. Not shared. (demo: https://codesandbox.io/s/peaceful-varahamihira-ywkmm)

zustand mentioned by u/cmdq will give you a shared state so will Redux.

What you trying to do seems can be implemented with Context as described by Kent C. Dodds's How to use React Context effectively.

KCD exposes dispatch but you can pass actions instead of dispatch in your case.

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

1

u/Patex_ Apr 02 '20

Can Error boundaries be placed inside the render function of pure components? I would like to set and forget about error handling in `Foo` will render be updated accordingly or do I need to wrap the entire component?

class Foo extends PureComponent {

  render() {
    return (
      <ErrorBoundary>
          ....
        </ErrorBoundary>
      );
    }
}

class ErrorBoundary{
  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
      ....
  }

  render() {
    if (this.state.hasError) {
      return (<h2>Could not display error</h2>)
    }
    return this.props.children;
  }
}

1

u/Nathanfenner Apr 02 '20

They can be placed anywhere (components are composable). But an error boundary in Foo's render won't catch errors thrown from within that render function, only from within the components in the tree it encloses.

1

u/cstransfer Apr 01 '20

Let's say I have a large json response from an api call that is stored in redux.

so something like this

candy.data = action.payload

The data is used in the entire application. I use selectors and mapStateToProps when a component needs the data.

export const getCandy = (state) => state.candy.data;

export const mapStateToProps = (state) => ({
candy: selectors.getCandy(state)
});

So a component would use it like this

{candy.type || ''}

{candy.order.test.value || ''}

Is having one reducer okay? The only time the redux value is updated is when we make another api call, and the redux value is overwritten with the new value

One of my team mates is trying to make a case for multiple reducers. So far he has created 30 reducers. He'll probably end up with around 45 reducers which is insane

3

u/wagonn Apr 01 '20

A single reducer is probably ok if you're just overwriting the entire state each time. Separate reducers are probably the better approach if any of your slices/substates need to change in a specific way.

→ More replies (1)

1

u/Niesyto Apr 07 '20

I wany to make an app with cooking recipes. Is single-page app a bad approach? I want users to be able to bookmark a recipe (as a regular bookmark in browser). How would I go about doing this? The recipes are kept in a database.

3

u/[deleted] Apr 07 '20

So the term "single page app" is a bit confusing as "page" doesn't refer to URLs, it refers to how many documents the browser fetches while you're navigating.

In other words, you can still have multiple URLs in your SPA. SPA just means that your server gives back the same html document no matter what URL you're on, and JS then decides what content to render based on the URL. Navigation is done in javascript, instead of requesting a new document from the server each time. So this gives you faster navigation (in theory) and possibilities for page change animations, etc. You can also better maintain state across pages.

So, yeah, SPA is fine for what you want. You'd probably use react-router. The only limiting thing is you'll need a server that can serve the same html regardless of the page you're on. This is easy to do with a nodejs server, but I don't know if it's possible with Github pages, for example. You could also use HashRouter to bypass this issue.

→ More replies (2)

1

u/noblepolygon Apr 07 '20

Hi, I'm trying to figure out why my nested data isn't mapping to the correct component.

https://stackblitz.com/edit/react-kt1zf8

Basically, each car should get its information added to the label above. However, it's currently only mapping the data for the first two cars in both rows.

I think the problem is here setAutoData(data.lanes[0].cars); because I think it's only looping through the first objects. I've tried removing the [0] which results in an error but I'm not sure where to go from here. Any thoughts? Thanks!

3

u/cmdq Apr 07 '20 edited Apr 07 '20

Couple of things:

In both AutoLabel and LaneInfo:

  • I'm not sure why you're using useEffect to set data in useState, but it's not necessary. You can use it as the first argument directly: useState(data.lanes.cars)
  • Similarly, checking whether autoData exists is not necessary. I'm guessing you added it because otherwise React complained about Cannot read property 'map' of null but that's only because you're initializing your state with null, instead of passing data directly.

Here's a quick fork that seems to do what you wanted: https://stackblitz.com/edit/react-lqienv

  • Check out how we're passing data down the tree via props, instead of requiring it.
  • Note also how we've pulled the <AutoLabel data={block} /> inside the map iteration, because it needs to be passed each car object as well.

Let me know if you have any questions!

→ More replies (1)

1

u/spcmnf Apr 09 '20

Hi, I'm new to React. I just finished a bootcamp where they mainly taught us to use hooks and basically skipped over class based components. When I try to find answers to my questions online mostly others have been using class based components.

Have hooks fully taken over and I should mainly be using that? Or, are class based components still just as valid in 2020 and I need to learn them well? I already feel like I need to learn them just so I can read documentation, blog posts, and understand youtube vids that use them. But should I be using them or just going with hooks?

6

u/[deleted] Apr 09 '20

Roll with hooks. But understand how class components work. Learn “this”, binding, and how to “setState” in a class component. There are the life cycles that you should understand. If you get hired you will want at least that basic knowledge. Convert a few class components to functional components with hooks and you’ll be good.

→ More replies (1)

1

u/ours Apr 11 '20

I'm currently learning React and from what I understand hooks and functional components are the way to go. Is there any reason not to use functional components whenever possible since with hooks we can do pretty much everything that class-based components can?

I'm certain there are a couple of exceptions where some specific lifecycle methods are needed but it seems for 99% of my components, whether they are containers or views I should go with functional components.

5

u/Awnry_Abe Apr 11 '20

Yes, full speed ahead using that understanding.

→ More replies (1)

1

u/Ciorap88 Apr 12 '20

Can using other functions inside functional components cause performance issues?

For example, in a class component you can have a handleClick method:

class button extends React.Component {
  handleClick = () => {
    // something
  } 
  Render() {
    return (<div>
      <button onClick={ handleClick } >
      </button>
    </div>) ;
  } 
}

Can writing the component as

Function button () {
  const handleClick = () => {
    // something
  } 
  return (<div>
    <button onClick={ handleClick } >
    </button>
  </div>) ;
}

cause performance issues? If so, how can I write this better?

3

u/cmdq Apr 12 '20 edited Apr 12 '20

The thing about performance issues is having them and not wondering about potentially having them. You're likely not building a physics engine in react. You're fine.

(The long answer is, yes, recreating functions could potentially come with a performance cost, but you're very unlikely to ever notice any kind of performance impact. Also, performance tuning is only ever valid if you actually measure before and after ;))

1

u/benihime-xbla Apr 13 '20

I have two material sliders that have to interact with each other. Say for example, slider 1 is 20, slider 2 will be 80. And say I change slider 1 to 80, slider 2 will be 20.

I set a default value for both of them. When I set a value though the slider doesn't move anymore.

const [slider1State, setSlider1State] = useState(100)

const [slider2State, setSlider2State] = useState(0)

<Slider

defaultValue={100}

value={slider1State}

onChangeCommitted={(e,v)=>{setSlider2State(100-v)}}

/>

<Slider

defaultValue={0}

value={slider2State}

onChangeCommitted={(e,v)=>{setSlider1State(100-v)}}

/>

Sorry this is probably a straightforward answer but I'm new to react.

4

u/Nathanfenner Apr 13 '20

You're only setting one value, so the other won't change. You want to do:

const [slider1State, setSlider1State] = useState(100)
const [slider2State, setSlider2State] = useState(0)

...

<Slider
  value={slider1State}
  onChangeCommitted={(e, v) => {
    setSlider1State(v);
    setSlider2State(100 - v);
  }}
/>
<Slider
  value={slider2State}
  onChangeCommitted={(e, v) => {
    setSlider1State(100 - v);
    setSlider2State(v);
  }}
/>

Note that you probably don't need defaultValue, since you're always setting value. Another option is to notice that you don't really need separate state for each (though depending on how your app evolves, you might find that you eventually do). In this case, only have one bit of state:

const [slider1State, setSlider1State] = useState(100)
const slider2State = 100 - slider1State; // no need for useState

...

<Slider
  value={slider1State}
  onChangeCommitted={(e, v) => {
    setSlider1State(v);
  }}
/>
<Slider
  value={slider2State}
  onChangeCommitted={(e, v) => {
    setSlider1State(100 - v);
  }}
/>
→ More replies (1)

1

u/[deleted] Apr 18 '20

I’m fairly new to react, and was wondering how scalable the MERN stack is? Ive made a simple website that has some users already, but I’m not sure if mongo dB is the best db if the user base increases?

4

u/cmdq Apr 18 '20

Measure performance. Don't wonder about it :) If your measurements indicate that mongodb is not fast enough for you, use something else!

1

u/Zz1995aJ Apr 18 '20

If I have a router from react-router-dom that looks like the following:

<Switch>
  <Route exact path = '/' component = {Home} />
  <Route path = '/question/:id' component = {Question}/>
  <Route path='*' component = {PageNotFound}/>
</Switch>

If I go to localhost:3000/question/1234, where 1234 is the id of a question that does exist, then it will display the Question component and not display the PageNotFound component. This is working as intended.

If i go to localhost:3000/invalidroute, where invalidroute is unsurprisingly an invalid route, then it will display the PageNotFound component. This is also working as intended.

However, if i go to localhost:3000/question/789, where 789 is the id of a question that does not exist, it will try to display a Question component for a question id that doesn't exist and it will not display my PageNotFound component. What I actually want is for the PageNotFound component to be rendered in this situation and nothing else.

I know why this is happening: despite the question id not existing, the address is still in a form that matches the route with path = '/question/:id'.

My question is then, how do I get around this? Is there a typical way this situation is handled?

4

u/cmdq Apr 18 '20

How is the route supposed to know that your question id does not exist? It can't tell. You'll have to handle the check for a valid question inside somewhere below the Route component, and then redirect yourself.

Alternatively, since react-router uses expressjs style routes, so you could do this: /question/:id(123|456). This tells react router that 123 and 456 are valid values for id. If you have a list of all valid question ids, this would work: /question/:id(${questionIds.join('|')})

But be warned that I have no idea how this performs with a potentially huge amount if ids, so apply common sense.

→ More replies (1)

1

u/GulyFoyle Apr 19 '20

Should i pursue learning best practices or master what i find reasonable and easier to understand for me ?

I've been trying to learn react for few months now , i started by class based components , lifecyclehooks and context api and now these are "older" methods replaced by funcional components, hooks etc.

It feels like im always starting over trying to find best practice in a rapidly changing enviroment and since i am not doing this professionally i have no idea what real world problems require.

Would appreciate any kind of advice on this matter, thank you.

3

u/cmdq Apr 19 '20

There's nothing wrong with class components, but you might find yourself missing important experience with function component and hooks. The React community seems to have collectively moved on to to using function components and hooks by default, and only using classes where necessary.

You would not be starting over, just continuing along the path of things to learn about react. I'd encourage you to keep going!

1

u/ShitHitTheFannn Apr 21 '20

I'm building a Gomoku game in React (it's like Tic-Tac-Toe but on much larger board). I use a multidimensional array to represent the game state. But since react does not permit mutability, I have to use Array.map() to mutate the game state which has O(n) time, which for a simple operation like this should be constant. Is there anyway I can mutate a specific cell in my array in constant time?

4

u/cmdq Apr 21 '20

Check out https://immerjs.github.io/immer/docs/introduction for a nice way to mutate state directly

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

1

u/Astral_Turf Apr 22 '20

Can someone post a definitive guide to conditional rendering? Something relatively advanced would be great. I clearly don't have a good handle on it because I can only get it to work by tweaking things haphazardly and then things tend to break in unexpected ways.

3

u/cmdq Apr 22 '20

Sure! Some questions beforehand: What exactly do you struggle with? Can you give us an example of something that would trip you up?

2

u/maxfontana90 Apr 23 '20

Conditional rendering is all choosing what to render inside a component.
https://reactjs.org/docs/conditional-rendering.html

Remember: If you are using hooks, you always run your hooks before the return statement, otherwise React will not have the ability to track side effect changes.

1

u/csvtom Apr 22 '20

Could you tell me please a real world examples about high order components; that kind of cases when you say "Yes, here is a good solution" Thank you <3

3

u/[deleted] Apr 23 '20

This article provides a very good explanation, you can check it.

https://levelup.gitconnected.com/understanding-react-higher-order-components-by-example-95e8c47c8006

I quote, A higher-order component in React is a pattern used to share common functionality between components without repeating code.

A higher-order component is actually not a component though, it is a function. A HOC function takes a component as an argument and returns a component. It transforms a component into another component and adds additional data or functionality. In short:

const NewComponent = (BaseComponent) => {
  // ... create new component from old one and update
  return UpdatedComponent
}

Here is the practical example of an HOC:

import React from 'react';

const withStorage = (WrappedComponent) => {
  class HOC extends React.Component {
    state = {
      localStorageAvailable: false, 
    };
  
    componentDidMount() {
       this.checkLocalStorageExists();
    }
  
    checkLocalStorageExists() {
      const testKey = 'test';

      try {
          localStorage.setItem(testKey, testKey);
          localStorage.removeItem(testKey);
          this.setState({ localStorageAvailable: true });
      } catch(e) {
          this.setState({ localStorageAvailable: false });
      } 
    }
  
    load = (key) => {
      if (this.state.localStorageAvailable) {
        return localStorage.getItem(key); 
      }
      
      return null;
    }
    
    save = (key, data) => {
      if (this.state.localStorageAvailable) {
        localStorage.setItem(key, data);
      }
    }
    
    remove = (key) => {
      if (this.state.localStorageAvailable) {
        localStorage.removeItem(key);
      }
    }
    
    render() {
      return (
        <WrappedComponent
          load={this.load}
          save={this.save}
          remove={this.remove}
          {...this.props}
        />
      );
    }
  }
    
  return HOC; 
}

export default withStorage;

Using it to wrap another component:

import React from 'react';
import withStorage from 'components/withStorage';

class ComponentNeedingStorage extends React.Component {
  state = {
    username: '',
    favoriteMovie: '',
  }

  componentDidMount() {
    const username = this.props.load('username');
    const favoriteMovie = this.props.load('favoriteMovie');
    
    if (!username || !favoriteMovie) {
      // This will come from the parent component
      // and would be passed when we spread props {...this.props}
      this.props.reallyLongApiCall()
        .then((user) => {
          this.props.save('username', user.username) || '';
          this.props.save('favoriteMovie', user.favoriteMovie) || '';
          this.setState({
            username: user.username,
            favoriteMovie: user.favoriteMovie,
          });
        }); 
    } else {
      this.setState({ username, favoriteMovie })
    }
  }

  render() {
    const { username, favoriteMovie } = this.state;
    
    if (!username || !favoriteMovie) {
      return <div>Loading...</div>; 
    }
    
    return (
      <div>
        My username is {username}, and I love to watch {favoriteMovie}.
      </div>
    )
  }
}

const WrappedComponent = withStorage(ComponentNeedingStorage);

export default WrappedComponent;

3

u/vijit-ail Apr 23 '20

Let's say that have a posts component that displays all the post. Normally what you would do is make the API request inside of componentDidMount() and show a loader until the data is fetched. You could abstract the data fetching by creating a higher-order component (HOC). This way your component doesn't have to worry about how to fetch the data. Another advantage of this approach is that you can use the HOC for other components as well.

→ More replies (1)

1

u/backtrack432 Apr 22 '20

Is there a way to programatically focus on input/textarea/texteditor when hitting a specific key like enter?

4

u/[deleted] Apr 23 '20

You use ref attribute in these situations. refs enable you to reference the DOM object in your react app, check the docs here for more information.

Then you can simply add a keyup event listener to document when your app / component mounts to the dom, in which the listener can check which key has been pressed and focuses the appropriate input element.

See this brief example, implementation with class and functional components https://codesandbox.io/s/ref-example-7w7k1

1

u/Vtempero Apr 23 '20 edited Apr 23 '20

I am willing to use Gatsby for a small pet project. Can you please help me understand some points:

  • what kind of differences can I expect coming from create-react-app?
  • what exactly "static" means as in "static site generator?" My understand is that Gatsby will create only one "build", instead of serving different js code ("builds") based in different requests endpoints.

thanks in advance.

edit: this page has all the answers: https://www.gatsbyjs.org/docs/porting-from-create-react-app-to-gatsby/

3

u/[deleted] Apr 24 '20

Heavy gatsby user and one of their largest corporate users (I believe).

  1. SSR gives you the ability to have a statically generated dynamic site. Huge for SEO etc. They also have an ecosystem of plugins (think like webpack) and routing mechanism (no need for react-router).
  2. static meaning it is serving an html/css/js file. If you look at a React site it is just the index.html which has one div that is called root (I think this is the most common pattern). This is great for SEO among other things.

Tangential I highly suggest Netlify to explore the deployment side of things. They are free for personal projects

1

u/GhostofBlackSanta Apr 25 '20

Hi I'm new to React and JavaScript coming from a C++/Java background. I'm taking a course on React but my biggest problem is understand what part of the code is React and what part is JavaScript. Is there an easy way to distinguish the two?

3

u/Higais Apr 25 '20

Well you work with React using JavaScript. In React you also use JSX to write HTML within your JS files. Within JSX, you can inject JS code using curly braces to add dynamic rendering to your HTML. So many acronyms! Anyway, maybe I'm misunderstanding it, but it isn't that one part of the code is React and one part is JS. You write React code for the most part with JS, but in your components, where you are actually rendering content and not just working with the logic, you have JSX, which looks like HTML but also has JS expressions and statements inside which are surrounded by {}. I hope that made sense, I'm a beginner too!

3

u/Awnry_Abe Apr 25 '20

Any thing you call/use that appears as an import in your code from 'react' or 'react-dom'. If using classes, which you will be drawn to as an OOP programmer, only to have your dreams dashed, you will likely create class based react components that derive from React.Component. Any of that classes methods/fields that derive from Component are React's. I don't want to simply dismiss everything else as "therefore, all the rest is JavaScript", because such a statement could drive you into a ditch. For the sake of this discussion, <FooBar> is definitely not JS but rather is React, but the truth is more nuanced than that.

Learning JS is your first order of business. It gets an un-warranted amount of hate from the "non-web" part of the globe. It is actually a beautifully functional language and is actually very challenging to learn. I cut my teeth on C, then C++, and have been programming daily for decades. I am reminded constantly by this language, "You don't know JavaScript".

Oh, you're gonna appreciate Typescript. Given your background, I'd start using it on day 1.

1

u/badboyzpwns Apr 28 '20

Goal

I'm creating a sign in or sign out button with Google's authentication. If a user is signed in. a sign out button would appear. If a user is signed out, a sign-in button would appear.

Problem

I always thought React hooks would essentially replace classes 99% of the time

But I think this code is not suitable for hooks because I only want to setup google's OAuth once at componentDidMount(). Using a hook will make me set it up multiple times, making it redundant.

Please let me know if I can transform it into hooks.

With classes:

class GoogleAuth extends React.Component {
  
    state = { isSignedIn: null };

    componentDidMount() {

//Set up google's auth
        window.gapi.load("client:auth2", () => {
            window.gapi.client
                .init({
                    clientId:
                        "XXXX",
                    scope: "email",
                })
                .then(() => {
                    //Checks if user signed in when page loads
                    this.auth = window.gapi.auth2.getAuthInstance();
                    this.setState({ isSignedIn: this.auth.isSignedIn.get()});
                    
                    this.auth.isSignedIn.listen(this.onAuthChange);
                    //listens if user signs in / signs out during a session
                 
                });
        });
//End of set up
    }

    onAuthChange = () => {
        this.setState({ isSignedIn: this.auth.isSignedIn.get() });
    };

    onSignIn = () => {
        this.auth.signIn();
    };

    onSignOut = () => {
        this.auth.signOut();
    };

    checkAuth() {
        if (this.state.isSignedIn === true)
            return (
                <button onClick={this.onSignOut}>
                    Sign Out
                </button>
            );
        else if (this.state.isSignedIn === false)
            return (
                <button onClick={this.onSignIn}>
                    Sign In
                </button>
            );
    }

    render() {
        return <div> {this.checkAuth()} </div>;
    }
}

With hooks:

const GoogleAuth = () => {
    const [isSignedIn, setIsSignedIn] = useState(false);
    let auth;

    onAuthChange = () => {
        // this.setState({ isSignedIn: this.auth.isSignedIn.get() });
        setIsSignedIn(auth.isSignedIn.get());
    };

    onSignIn = () => {
        auth.signIn();
    };

    onSignOut = () => {
        auth.signOut();
    };

    checkAuth = () => {
        if (this.state.isSignedIn === true)
            return (
                <button onClick={onSignOut}>
                    Sign Out
                </button>
            );
        else if (this.state.isSignedIn === false)
            return (
                <button onClick={onSignIn}>
                    Sign In (With Google)
                </button>
            );
    };

    useEffect(() => {
        window.gapi.load("client:auth2", () => {
            window.gapi.client
                .init({
                    clientId: XXX,
                    scope: "email",
                })
                .then(() => {
                    //Checks if user signed in when page loads
                    auth = window.gapi.auth2.getAuthInstance();
                    setIsSignedIn(auth.isSignedIn.get()); 

                    auth.isSignedIn.listen(onAuthChange); //listen if user 
              signs in / signs out during a session
                });
        });
    }, [isSignedIn]);

    return <div>{checkAuth()}</div>;
};

4

u/[deleted] Apr 28 '20

Generally speaking, if you only want an effect to be called on mount, you pass an empty array as the second argument: useEffect(myEffectFn, []).

In your case, you did: useEffect(myEffectFn, [isSignedIn]). Meaning myEffectFn gets called initially once, and then every time isSignedIn changes. Since your effect is changing isSignedIn AND at the same time being triggered by it, you got yourself an indefinite loop.

→ More replies (1)

1

u/geo_n1ght Apr 28 '20

Hello. Quick question.

I want to connect a React UI to a backend that gets data from another system. The UI will only read data from the backend but I want it to query the backend somehow and auto update without clicking any button (auto update ?). Where shoulf I look because I have no idea where to start?

2

u/[deleted] Apr 28 '20

either you do some polling, or you could check out websockets

→ More replies (1)

2

u/cmdq Apr 29 '20

There's also server sent events if you want your backend to notify the frontend of new data, and don't need the bidirectional communication that websockets gives you

1

u/Jorick_DC Apr 29 '20 edited Apr 29 '20

Quick question

I am trying to build following functionality. on your screen you have two buttons A and B. When you press button A, form A should appear instead of the buttons. And when you press button B, form B should appear. How do I best do this?

I was thinking along the way of conditional rendering.

2

u/Nathanfenner Apr 29 '20

Yes, something like:

function FormPicker() {
  const [formChosen, setFormChosen] = React.useState(null);

  return (
    <>
      {!formChosen && (
        <>
          <button onClick={() => setFormChosen("A")}>Form A</button>
          <button onClick={() => setFormChosen("B")}>Form B</button>
        </>
      )}

      {formChosen === "A" && <FormA />}
      {formChosen === "B" && <FormB />}
    </>
  );
}

You should also consider making an affordance for "going back" if the user initially picks the wrong form (theres' few things worse in UX than trying and failing to undo a decision/action that initially seemed harmless).

→ More replies (1)

1

u/badboyzpwns Apr 30 '20 edited Apr 30 '20

1.is it a good idea to always use anonymous functions for helper functions? I just wanna avoid the "this" bind error sometimes.

2. Aside from the benefit of manipulating this.setState(); are classes just syntatic sugar for functional components? Does it matter if I use classes for everything (let's ignore the fact where react hooks can be more efficient in some cases). Will it slow down performance?

3

u/[deleted] Apr 30 '20

are classes just syntatic sugar for functional components

Syntactic sugar is usually used when referring to new syntax making some old feature better, but in this case hooks are newer and arguably more convenient than classes. So you could say that classes are... Syntactic pepper? :D

The point is, you can do almost everything with both (function components also have state with hooks), so it's personal preference. However keep in mind that hooks are basically here to replace class components and the community is moving towards those. So unless you have a good reason to use classes, your default should be hooks moving forward. Not for performance reasons, but for reasons of readability, better code reuse, and being more in line with what everybody else is doing. The React docs go into more detail about the benefits of function components (and hooks).

As for the anonymous functions: I assume you mean arrow functions? It's fine, I guess. I've personally only used them for callbacks, that way I can tell that if a class method is an arrow function, it's being used for a callback. But I doubt anybody else joining the project would have picked up on that. It might even be better to stay consistent and make them all arrow functions.

→ More replies (1)

1

u/sssmmt Apr 30 '20

I've come across this compound component that's configured using special children components. It looks like this:

<Grid data={fetchRows}>
  <Grid.Columns>
    <Grid.Text field='name' />
    <Grid.Url field='url' />
  </Grid.Columns>
  <Grid.Pagination pageSize={10} />
  <Grid.Filter onQuery={handle Query} />
</Grid>

What's the name of this pattern? How does parent Grid change its behavior depending on its children?

0

u/[deleted] Apr 14 '20

[deleted] — view deleted comment

2

u/dance2die Apr 14 '20

You can use Context or prop-drilling if a state doesn't change often for the former, and the state can be passed down to a child, not too deep (prop-drilling).

But at this point you know React enough to know how global state management libraries such as Redux, MobX, Zustand can come in handy so researching those libraries might be of help.

2

u/2jumph Apr 14 '20

You can do something called 'prop drilling' where you pass your state down as props trough every single nested component or you can implement a state management solution like reacts own context or redux.

0

u/[deleted] Apr 20 '20

[deleted] — view deleted comment

2

u/dance2die Apr 21 '20

You might want to check out the official documentation, Integrating with Other Libraries.

0

u/[deleted] Apr 29 '20

[deleted] — view deleted comment

5

u/[deleted] Apr 29 '20

when you first download project from gitGitHub you must install the page. go to the project on your folder and type "npm install" on terminal. that would download all the dependencies and then you will be able to start with "npm start"

3

u/khalant1989 Apr 29 '20

Oohhhh gotcha! Wow. Thanks a lot instantly worked right after

→ More replies (1)

0

u/[deleted] Apr 04 '20

[deleted] — view deleted comment

1

u/dance2die Apr 06 '20

A question (how not to clear)? or a comment (a frustration)?

→ More replies (1)

2

u/[deleted] Apr 20 '20

[removed] — view removed comment

2

u/dance2die Apr 21 '20

Only during a quick & dirty demo. Too high of a specificity (only second to !important)

→ More replies (2)

1

u/[deleted] Apr 08 '20

[removed] — view removed comment

3

u/cmaronchick Apr 08 '20

Firebase is a backend system built by Google that provides almost everything you need to support a React app out of the box, including:

  • Authentication
  • Node JS Functions
  • NoSQL Database
  • Analytics

I just went through the process of building an app (it needs polish and a few more features to complete after which I'll share), and I really liked using Firebase with CRA.

→ More replies (2)

2

u/Astral_Turf Apr 09 '20

For me, a baby developer, Firebase is AMAZING. It lets me not have to build a back-end. It's various pieces handle everything I would need. So it lets me produce complete apps with less skill and of course less work.

But it's not just for losers like me! AFAIK it's great for 'real' apps too. One great thing about it is scalability. It scales for you because you're not running your own software on a server somewhere that requires your maintenance. It's also pretty much free unless you've actually got some real traffic.

0

u/[deleted] Apr 19 '20

[deleted] — view deleted comment

1

u/cmdq Apr 19 '20

forEach does not return anything, so the <Key /> element you return is thrown away.

You want to use .map instead. It returns an array of the elements you returned inside the iterator function.

The idea is that you transform your list of data into a list of equivalent UI elements.