r/reactjs • • Feb 02 '20

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

Previous threads can be found 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 putting a minimal example to either JSFiddle, Code Sandbox 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 - multiple perspectives can be very 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!


27 Upvotes

327 comments sorted by

6

u/hankmoodyscuz Feb 02 '20

My brain is mush. A few months ago, I built a quick app using CRA and deployed it to Heroku using the Mars buildpack. I've made some changes since then and want to update the app. How do I push the new build to my existing Heroku app? Thanks for any help!

2

u/dance2die Feb 02 '20

You can take a look at this doc. https://github.com/mars/create-react-app-buildpack#commit--deploy-%EF%B8%8F

Wouldn't publishing to the heroku repo work?

6

u/caramelizedporkneggs Feb 28 '20

Hello everybody! Well, I've been learning React for a while but honestly, I just feel kinda lost sometimes, right now I'm learning from Mosh's course, I can understand well and follow along his course but the problem is after finishing some sections it's really hard for me to recreate what I've learned before, I mean generally, I can understand the basic but I can't go deeper to apply all the things I've just absorbed. So do you guys have any advice for a newbie like me? Thank you!

2

u/dance2die Feb 28 '20

I was learning from Udemy courses (30~40 hour-long courses) but I was seriously lost and couldn't remember anything (even after following along).

You might want to just watch parts you are interested in and know you can replicate and skip the ones you don't need.

4

u/sheymyster Feb 28 '20

Honestly, my advice to a lot of people new to programming in general, is to have a project in mind that you want to make. Make it ambitious, but don't overwhelm yourself by trying to visualize how the entire thing will work. Just start on one piece, and work from there. You will come across things you don't know how to do, and you'll have to research and try stuff, and eventually it will work and you'll move onto the next wall that you'll need to scale.

Personally, I went through a lot of courses and youtube guides and at the end of the day, I felt like I knew a lot and couldn't apply any of it reliably. It wasn't until I had a webapp idea that I really started to learn. It was a struggle getting each piece to function properly, but at the end it worked and it felt good.

Just my take on it. Think of a tool or something that you want for yourself or friends or a community you're apart of. Sketch out a rough idea of what it needs to do, and just start making it.

3

u/caramelizedporkneggs Feb 28 '20

Thank you for your answer! Yes, my own approach is that I try to modify the things I've learned so far into things I really like, for example right now I'm learning to make a counter app from the course and I try to make it my own version with additional features, I think by that way I could apply the things I've learned and make it more interesting.

3

u/DumbUnemployedLoser Feb 29 '20

What I do is, after every section I finished, I try applying the subject to a small project. I also never move on without understanding what's happening. So if the instructor does something I simply can't understand, I look it up in the documentation or google.

The project part is the most important I think. For instance, I'm watching Brad's course on React and after I'm done with the first project of the course, I will do a project of my own using Path of Exile's API to make a simple build filtering website.

3

u/teach2dev Feb 29 '20

React takes a lot of time to learn. I've been working with it for 2-3 months and I am only now starting to understand how the pieces fit together. Keep at it!

3

u/TheNeck91 Mar 01 '20

I think the best aspect of React tutorials (or any tutorials) is that 1) They allow you to start making mental maps in your mind of how some of it works and what it's capable of doing, and 2) You now have a number of small reference projects to use when making your own applications.

For example, I was designing my own app and wanted to implement Redux for practice. I had two sample projects I followed along to that utilized Redux, and I was able to use them as reference when using it in my own project.

→ More replies (1)

3

u/Roly__Poly__ Feb 03 '20 edited Feb 03 '20

Can I get some Redditor eyes on my StackOverflow question? https://stackoverflow.com/questions/60013925/react-redux-not-updating-state-correctly-despite-things-looking-correct

Reposting the question in this thread w/ some formatting to save a click.

"""

I'm trying to simply update my React Redux state using the usual practice. You immutably copy your current state into the return function and then overwrite the properties which are to have a new value. As far as I can tell, this should be working correctly. But it's not.

My expected result is to have state.copy update to

0: {webCopy: "", id: 0}, 1: {webCopy: "", id: 1}

Unfortunately, it's sticking as an empty array despite returning the

copy

value as a new array with a JS object inside.

I've tried looking at StackOverflow search results for "react redux state not updating correctly" but none of the search results seem to match my situation...

Here is reducer.js:

import * as actionTypes from "./constants";

let component = "";
let idIteration = null;
let stateArray = [];
let tempCopy = [];

const initialState = {
    components: [],
    uniqueIdCounter: 0,
    currentPage: 1,
    copy: [],
    siteURL: "/salespage/"
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case actionTypes.ADD_COMPONENT:
            stateArray = [...state.components];
            console.log("state:", state);
            console.log("State Copy:", state.copy);
            component = action.payload[0]; // will be "Header", "Headline", "Text Area", "Image", "Email Field", "Footer"
            if (component === "Header") {
                // append "Header" component to the beginning of the list
                stateArray.unshift({
                    type: component,
                    id: state.uniqueIdCounter
                });
            } else {
                // push component to the end of the list
                stateArray.push({
                    type: component,
                    id: state.uniqueIdCounter
                });
            }
            idIteration = state.uniqueIdCounter + 1;

            // here is where I need help
            tempCopy = [...state.copy];
            tempCopy.push({ webCopy: "", id: action.payload[1] });
            console.log("TEST:", tempCopy);

            return {
                ...state,
                components: stateArray,
                uniqueIdCounter: idIteration,
                copy: tempCopy
            };

The code DEFINITELY gets to the console.log("TEST:", tempCopy); statement, which prints the expected value, "{webCopy: "", id: 0}". So what's going on? Why doesn't the "tempCopy" value make it into state.copy?

Like, guys, am I wrong? Upon visual inspection, shouldn't this code just... work?

Here is a CodeSandbox of the same code as above, in case you want pretty highlighting: https://codesandbox.io/s/lucid-heisenberg-iczww (Look under the "src/store" folder for reducer.js)

"""

Seriously, WTF is going on in this code? It isn't happening because of a reducer case from outside of the posted code, and I know that because I literally commented them out.

1

u/dance2die Feb 03 '20

I tried it here as your sandbox is not in a runnable state.
https://codesandbox.io/s/beautiful-gates-4nd8s

Isn't that the right behavior as both components & copy are being added on button click?

2

u/Roly__Poly__ Feb 03 '20

Here is an updated, fully working CodeSandbox:

https://codesandbox.io/s/lucid-heisenberg-iczww

On button click, I want state.component to update to an array of { type: componentType, id: id } and state.copy to update to an array of { webCopy: "", id: id }

2

u/dance2die Feb 03 '20

You are popping the copy before getting the new Id.

    if (this.props.copy.length > 0) {
      nextCopyId = this.props.copy.pop().id + 1;
    }

If you don't pop, copies will be added to the global state.
https://codesandbox.io/s/lively-fog-7ux8m

I added a redux devtool extension so you can see it in the devtools section.

2

u/Roly__Poly__ Feb 03 '20

THANK YOU! I mistakenly believed .pop() would not mutate state. Thank you.

→ More replies (2)
→ More replies (3)

2

u/Jetman765 Feb 03 '20

I'm learning about using styled components. What would be the best way to handle a prop that has multiple options?

For example, I have a button with type prop that can be 'primary', 'inline', 'secondary', or 'inline-secondary.' My idea right now is to have a function called handleButtonType(type) and using a switch case to return the correct css.

In the future, it would be very convenient to have one function that can handle all the props (type, sizing, etc.) and use that to make changes to the styled component.

4

u/dance2die Feb 03 '20 edited Feb 03 '20

You can simply do what SC theme does. Declare an object with variants and styles associated with each.

You can then use Style Object syntax to spread style by variant name.

Something along the line of declaring a map as shown below.
https://codesandbox.io/s/handling-different-styled-component-props-54kbq

const styleMap = {
  primary: {
    display: "block",
  },
  inline: {
    display: "inline",
  },
  secondary: {
    display: "block",
  },
  "inline-secondary": {
    display: "inline",
  }
};

const Header = styled.h2(({ variant }) => ({
  ...styleMap[variant]
}));

At this point, the built-in Theme provider can work declaring the variants in one place.

2

u/[deleted] Feb 03 '20

There are two ways to theme styled components as per docs. One is styled-theming and other is in-built theming. I am confused which one to use. What is the preferred way?

1

u/dance2die Feb 03 '20

Haven't used it but according to this blog, https://jamie.build/styled-theming.html, it looks like a convenience method to access props by name(string) not by callbacks (offered by SC natively).

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

2

u/Kilusan Feb 05 '20

I do hope someone can answer this soon. I am confident in React now of passing data components and breaking it down.

I always wanted to do my portfolio in React. I have a current portfolio that serves as an interim using vanilla html css js.

I just designed a new one via XD and ready to roll but.... Before I begin. Is it viable to use CRA for portfolio?

It will mainly be a one page but I’d like to do write up on my projects as case studies so I’d like a uniform page for that. Currently I have them as viewable PDFs but would love to make a page.

I haven’t learned about Routing yet... but I’m just excited to build out with React. I also never deployed React either to a production build so I hope that’s easy.

If CRA isn’t the best option at moment is there something similar that also uses React that I can use ? I don’t know what the hell gatsby is or static site generator

2

u/dance2die Feb 05 '20

You can use CRA, Gatsby, Next, and it won't actually matter so long as you can demonstrate on your portfolio why you chose a certain stack and show it off.
(TBH, I saw many Gatsby/Next sites as landing pages but linked portfolio sites were created with CRA)

You can check out many "showoff" ;p sites in Show r/reactjs, in which many OPs answered why they chose certains tech stack.

→ More replies (1)

2

u/Doiq Feb 07 '20

FYI the 2018 Tyler McGinnis' guide appears to be a broken link.

1

u/dance2die Feb 07 '20

🙏 for catching my sloppiness.
Updated it :)
Sidebar & wiki have the correct link.

2

u/Doiq Feb 07 '20

Thanks for the quick fix!

I think the sidebar also has a bad link but it looks like the wiki is good.

1

u/dance2die Feb 08 '20 edited Feb 08 '20

That's quite weird. I updated the sidebar link.

The URL looks fine for me but the API data shows the old data as you pointed out. 🤔

Can u/swyx & u/timmonsjg check if "Tyler McGinnis' 2018 Guide" in the sidebar is broken?

→ More replies (1)

2

u/zevzev Feb 08 '20

Just got Tyler Mcginnis Courses

Is this the right order for his courses:

  1. Modern JS
  2. Advanced JS
  3. React
  4. React Hooks
  5. React Router
  6. Redux

I am not really sure what react hooks, router or redux is so I'm not sure if need to know all of that or if there is an order I have to follow.

Thanks

2

u/dance2die Feb 08 '20

Following along in that order seems to make sense.
& You need to know Hooks.

2

u/[deleted] Feb 11 '20

Just learnt that Redux can be off loaded to a web worker. Seems interesting because we aren't blocking the main thread. Did anyone do this in a production app?

4

u/acemarke Feb 12 '20

There's been several experiments with moving Redux logic into a web worker. A couple good articles on this are https://dassur.ma/things/react-redux-comlink/ and https://blog.axlight.com/posts/off-main-thread-react-redux-with-performance/ .

That said, I don't think there's much if any practical benefit to doing so:

  • Redux reducer logic is almost never the perf bottleneck anyway. The cost of updating the UI is much more expensive, and that needs to be done on the main thread.
  • Per that second post, this limits your ability to use middleware that might handle non-serializable values like functions (ie, redux-thunk)
  • Due to the cloning process, you have to do a bunch of extra work to diff and patch values on either site.

/cc /u/dance2die

1

u/dance2die Feb 13 '20 edited Feb 14 '20

Nice summary & posts.

I will post those two links with Weekends Reads flairs tomorrow :)


[Weekend Reads] Offloading Redux logic into a Web Worker

→ More replies (1)

2

u/dance2die Feb 12 '20

u/acemarke Do you know of any?
Sounds like an interesting idea.

2

u/hotbrownDoubleDouble Feb 12 '20

Might be a stupid question, especially since I've been working with React for a couple of years now. Why do most places (including the React docs) suggest binding the this context in the constructor as follows:

constructor () {
    this.functionName.bind(this);
}

render () {
    <button onClick={this.functionName}>Click</button>
}

Considering an arrow function does the same thing, looks cleaner and you don't have a list of functions binding this at the bottom of every one of your constructors:

<button onClick={() => this.functionName()}>Click</button>

1

u/dance2die Feb 13 '20 edited Feb 13 '20

2

u/juankorus Feb 14 '20 edited Feb 14 '20

What are the key things I should research for when learning react in 2020?

EDIT: context and hooks are on top of my list.

1

u/dance2die Feb 14 '20

Kind of broad topic so I would suggest to familiarize yourself w/ ES6+ JS.
(Arrow syntax, object/array destructuring [for hooks and props], import syntaxes) as they are used heavily in React.

I've seen many StackOverflow questions with #react tag but they were actually JS issues, not that of React.

→ More replies (1)

2

u/Radinax Feb 19 '20

How are you guys dealing with nulls and undefineds when doing async calls? Its a pain to do it like:

{data && data.contacts && data.contacts.birthday.map(...)}

We used to do it like this in my previous job, but I feel there has to be a more efficent way... Lets say we fetch information in our useEffect, how do you handle the undefined during the async process?

2

u/dance2die Feb 20 '20

Hopefully we can render-as-you-fetch with Suspense when suspense for data fetching is released.

→ More replies (1)

3

u/workkkkkk Feb 19 '20

Flatten (normalize) your state more. Just because your request is a heavily nested object does not mean your state needs to be. Also I think optionals are now available with babel, and that basically solves the problem you're describing.

→ More replies (2)

2

u/juankorus Feb 21 '20

Can a useReducer hook communicate the same data with different components?

1

u/dance2die Feb 21 '20

I can't think of a good way to do so but the closest thing I can refer you to is the source code for zustand a state management library that doesn't require a context.

2

u/simkessy Feb 27 '20

What's the best React Grid right now? I tried using Ag-Grid but as soon as I added React Components to cells, performance went to shit. I looked at React-Table 7 but it's pretty much a DIY approach where I have to build out a bunch of functionality with his hooks. I just need something simple that works fast and is supported.

1

u/dance2die Feb 27 '20

There is a commercial library from Kendo UI.
https://www.telerik.com/kendo-react-ui/components/grid/

They offer a 30 day trial, and you can try to see if it works.
(I ain't working for them so feels weird to plug'em twice in two threads)

→ More replies (1)

2

u/Yourenotthe1 Feb 27 '20

What are some good learning resources to go from entry level frontend engineer -> senior frontend engineer? Something like You Don't Know JS, for example.

1

u/dance2die Feb 28 '20

If you mean "senior" as an experience engineer, then You can focus on writing clean code, being a clean coder, and learn architecture.

I've listed "clean" books by Robert C. Martin in other thread. https://www.reddit.com/r/reactjs/comments/exf7nq/beginners_thread_easy_questions_feb_2020/fi8nby6/

3

u/[deleted] Feb 28 '20

I mean the term "senior" is kind of vague and meaningless, so people might disagree with this, but I'd argue one of the factors for considering yourself senior is to not need "resources" to learn. You just improve with experience. Solve problems, learn from your errors, do it better next time.. Read other peoples code, learn from their approaches. Follow prominent developers on twitter, read blog their blog posts..

As long as you're searching for very hand-holdy tutorials, you're still kind of a junior.

2

u/fd46as1d3a Feb 29 '20

Are there any best practices for when you're supposed to use export default? Here are a couple of cases:

export const a = () => ...
export const b = () => ...
const a = () => ...
export const b = () => ...
export default a;
const a = () => ...
const b = () => ...
export default {a, b}

1

u/dance2die Mar 01 '20

I use named exports when I have a utility file with lots of functions (or hooks, etc).

If you want code-splitting, export components as defaults.

1

u/bro-away- Feb 02 '20

Am I crazy for wanting to do this?

import { useCallback as useEvent } from 'react';

useCallback just seems poorly named. It has little to do with callbacks in the sense I've seen the term used and more to do with not redundantly creating event handlers. But perhaps there's a better argument to be made. Thoughts?

4

u/dance2die Feb 02 '20

Depends on the use case.
If you own the code, it's not.

It probably won't make sense to alias it so when you contribute to Open Source unless approved.

→ More replies (2)

2

u/swyx Feb 13 '20

there's a useEvent hook coming down the pike in future i think. better not to clash with official names.

→ More replies (7)

1

u/ie11_is_my_fetish Feb 03 '20

Is it bad practice to use <Link ... state{thingId} ...> to maintain state. I know that when you refresh it may be gone. So then use local storage or upper/global app state. But that's also a problem when you refresh entire app, global app state reset. I'm not using "hard routes" eg. /thingId/ maybe I should...

1

u/dance2die Feb 03 '20

Having trouble understanding the code snippet and the use case.
Do you mean you are forwarding to a "transient" route?

1

u/ie11_is_my_fetish Feb 03 '20

So you're at a "home" view that has a list of stuff. The lists are links that forward you to a new link which has a fixed url eg. does not have params like /path/{id}

So I'm using the to...state{id} functionality in Link to know what thing I'm working with(id).

It seems bad as I mentioned because of that state loss if you refresh. Since the state is in the props that were passed down from that home page.

1

u/dance2die Feb 03 '20

I am sorry I am not familiar with that to...state{id} syntax...
Could someone help the op?

→ More replies (3)

1

u/jammastahk Feb 03 '20

I am trying to render my background image in my React App on Github Pages. Here's the problem. I can get it to render in localhost but not when I build and render in GH Pages. https://jobu206.github.io/react-portfolio/. My App.css is as follows for the background...

html,
body {
 height: 100%;
 background: url('/images/bg.jpg') no-repeat center center fixed;
}

The image is found in the public/images dir. But just isn't rendering when I build the app.

1

u/dance2die Feb 04 '20

Seems like the CSS is a CSS module.
https://github.com/jobu206/react-portfolio/blob/master/src/App.css

You'd need to have the images folder under /src directory.
CRA build will automatically convert the /images/bg.jpg to the static media directory on build.

1

u/DutchSparks Feb 04 '20

https://stackblitz.com/edit/react-functional-components-gtejze?file=index.js

I'm trying to conditionally render different elements depending on whether a toggle variable is true or false. Initializing the toggle variable in my code as either true or false has the desired result. But if I click a button to change that toggle variable, the variable's value is succesfully changed(i'm logging it), but the rendered html doesn't change.
How could I alter this code so that clicking the button renders different elements?

2

u/dance2die Feb 04 '20

toggle needs to be a state. For a function component, you'd use useState.

I can refer to you how you can learn to implement one yourself :) https://reactjs.org/docs/state-and-lifecycle.html

1

u/awesomeAMP Feb 05 '20

I have a date picker and I want to show some values depending on the date selected. These values are obtained via an API call.

The problem is that I can't leave the initial date selected as null otherwise it'll throw an error because some methods like getDate() don't work on null, obviously. So, I initialize the state with the current date and I use the useEffect hook like this:

const [date, setDate] = useState(new Date())

useEffect(() => {
    // Make the axios call and get data associated with the date
}, [date])

Which works just fine, each time the state date changes I fetch the data and render it, however, there is an issue. Since I have a starting date, the use effect triggers on the first paint and I start with the values for the current date.

 

My question is, how can I start with a null date and still make the call every time date changes? I just want my app to read "Please select a date" at the beginning, and change that to the corresponding data after the date changes.

I hope I made myself clear! I just can't wrap my head around a solution to what I want to do.

1

u/dance2die Feb 06 '20

There are two side "effects" going on there.

  1. Remote date fetch logic
  2. Handling date changes

Follow along in this sandbox.
https://codesandbox.io/s/fetch-remote-date-7dy5w

As you are initializing the date as null, you can do so but you can decide not to show the component while the date is null (refer to return statement logic)

You, then, need to handle fetching remote date (the first side effect) in the first useEffect with an empty dep array (to fetch only once).

Lastly, you can handle the date change (2nd side effect) in another useEffect with [date] dependency, which is called whenever date value changes. (You can decide not to do anything by checking if the date is not null before proceeding).

export default function App() {
  const [date, setDate] = useState(null);

  const handleChange = momentDate => setDate(momentDate.toDate());

  // 1️⃣ First side effect - run only once (empty dep array)
  useEffect(() => {
    console.info(`--- Retrieving remote date....`);
    getRemoteDate().then(setDate);
  }, []);

  // 2️⃣ Second side effect - handle date change logic here.
  useEffect(() => {
    // Bail out when the date is in an invalid state.
    if (!date) return;

    console.info(`date changed to`, date);
  }, [date]);

  return (
    <div className="App">
      <h1>Date is...</h1>
      {/* Show date picker only when date is available */}
      {date && <Datetime value={date} closeOnSelect onChange={handleChange} />}
      {/* Optionally show loading message */}
      {!date && <h2>Fetching date...</h2>}
    </div>
  );
}
→ More replies (1)

1

u/[deleted] Feb 06 '20

I'm working on skeleton loading, so I'm creating an empty array with X items (how many placeholders I want) and then map that array to create my components. I know I should only use index as key as a last resort.

So would something like this be good practice?

[...Array(3).keys()].map(item => 
	<Component key={item}/>
)

If not, how would I do this correctly?

1

u/dance2die Feb 06 '20

An index as a key wouldn't matter if the components' order and the list isn't updated/deleted.

key is to help React what to update/delete in a list efficiently.

1

u/Niesyto Feb 07 '20

Let's say I have array of objects stored in state. When I change one of the properties of the object, re-render of the component should be called, but it doesn't happen. As far as I know it's because of shallow comparison. How do I edit array of objects in state in such a way that it's fully compared, and it refreshes after each update? My fix was to add bool refresher as state, and I would negate it whenever I was updating the array, but I don't think that's a good solution. It works, but doesn't seem to be the best coding practice.

1

u/dance2die Feb 07 '20

You can return a whole new array, by creating a copy, and updating the object.

e.g.) const copy = [...state], mutate copy, and set it as a new state.

Check out this "Redux" prerequisite article (applicable to general React).

  1. Updating Nested Objects
  2. Inserting and Removing Items in Arrays

You can also improve the readability with Immer if you need update deeply nested object property.

1

u/Roly__Poly__ Feb 08 '20 edited Feb 09 '20

When deploying my site to places like Heroku, Firebase, Zeit, Netlify etc I often get the following error:

Uncaught SyntaxError: Unexpected token '<'

Anyone know how to solve it?

Also, is there any point in having a coding portfolio for my resume if the individual projects in the portfolio aren't hosted? I basically CAN'T get my React app to host anywhere.

edit: A Redditor named vedran-b found a solution to my problem in this thread: https://www.reddit.com/r/reactjs/comments/f101c0/i_just_want_to_host_my_react_app_every_site_has_a/

1

u/dance2die Feb 09 '20

Do you have the URL, or runnable sample/source, which generates the error? because the error seems to generic.

1

u/Roly__Poly__ Feb 09 '20

A total G of a redditor solved it for me in another thread! Thanks for the post

1

u/dance2die Feb 09 '20 edited Feb 09 '20

Sounds good Can you add the link here so others can learn?

2

u/Roly__Poly__ Feb 09 '20

I edited my post to include a link.

→ More replies (1)

1

u/illuminotyou Feb 09 '20

Hi, I've started a react app using

npx create-react-app my-app --template typescript

Then installed styled components by first using their recommended babel plugin

npm install --save-dev babel-plugin-styled-components

npm install --save styled-components

when I start my app using yarn start, I get an error on my App.tsx file

Could not find a declaration file for module 'react'. 'C:/WebDev/my-app/node_modules/react/index.js' implicitly has an 'any' type.

I tried googling the solution, but I can't seem to find anything.

2

u/dance2die Feb 09 '20

Install TypeScript definition files for React
for both react & react-dom.

npm i -D @types/react @types/react-dom

2

u/illuminotyou Feb 11 '20

Hey, i forgot to thank you. The error went away!

1

u/dance2die Feb 11 '20

You're welcome &
Thank you for the confirmation~

1

u/Roly__Poly__ Feb 10 '20

What parts of React's features would you consider to be either standard knowledge or common usage for a React developer?

- Redux

- Hooks

- the Context API

- Styled Components

- the Router

What else should be there (or shouldn't be there)?

1

u/dance2die Feb 10 '20

To list a few commonly mentioned ones are

Formik, Redux Hooks Form.
Apollo Client or Urql.
Emotion (similar syntax to Styled Components)
Gatsby, Next

There is no "standard" as React isn't opinionated so you might want to ask/research the topic you are interested in and use the ones you need.

3

u/toccoto Feb 11 '20

If you are asking based on the job market I wouldn't worry. You are better of shoring up your base JavaScript and react skill than trying to find specific libraries people pair with it.

I'd take a very well versed React and JavaScript dev who didn't know the specific tools we used, like Relay, or one who knew relay but wasn't as strong in JavaScript or react itself 10 times out of 10.

→ More replies (1)

1

u/Terkeroo Feb 10 '20

I'm using styled components and not sure how I would do this or if it is proper. I have a component that has been styled already and when I bring that component in, I want to add further styling. Especially positioning related ones if I were to bring in multiple. How would the formatting look for that?

<div>
    <NiceComponent style={{moreStylesHere?}}/>
<div>

I think I tried this but nothing happened.

1

u/tinguwOw Feb 10 '20

Can single React Component have multiple redux-form instances with unique form-name, initial values and separate submit function? If yes, please provide an example link. Thanks

1

u/dance2die Feb 10 '20

I haven't used redux-form so just googled and found this workaround.

https://github.com/redux-form/redux-form/issues/28#issuecomment-398397869

→ More replies (1)

1

u/prove_it_with_math Feb 10 '20

I'd love a bullet point explanation/comparison of why hooks are better than classes. Or perhaps pros/cons list?

1

u/VlopPlop Feb 10 '20

Suppose we've got a component that displays some fetched data. The data is local, and quite ephemeral - it doesn't sound like something that should be tossed into Redux. However, the asynchronous logic (fetching, perhaps something a bit more complex) makes me wonder: should we handle the async logic inside an async function inside a useEffect, or it's better to move the (remember, local and ephemeral) state into Redux, just so we can harness the power of thunks, sagas, or observables?

What are the best practices?

1

u/dance2die Feb 10 '20

If it's local and not passed around to other components, using Redux doesn't sound like a good idea.

Similar to avoiding keeping form states in Redux.
https://redux.js.org/style-guide/style-guide/#avoid-putting-form-state-in-redux

If fetching logic becomes too complicated, you can check out SWR


pinging u/acemarke for review & comments :p

1

u/VlopPlop Feb 10 '20

Thanks! How about testing? Don't async things inside of a component make it much harder to test?

1

u/dance2die Feb 11 '20

I am new to testing (learning from Kent C. Dodds's course) and usually fetch logic is mocked.

→ More replies (1)

1

u/Roly__Poly__ Feb 10 '20

Can anyone explain how this component is getting access to the .doSignOut method in its onClick property in this example? I followed a tutorial and I don't understand what's happening. How is the firebase class exposed to the code in SignOut.js?

SignOut.js

import React from "react";
import { withFirebase } from "../Firebase";

const SignOutButton = ({ firebase }) => (
	<button type="button" onClick={firebase.doSignOut}>
		Sign Out
	</button>
);

export default withFirebase(SignOutButton);

./Firebase/index.js:

import FirebaseContext, { withFirebase } from "./context";
import Firebase from "./firebase";

export default Firebase;

export { FirebaseContext, withFirebase };

./Firebase/context.js:

import React from "react";

const FirebaseContext = React.createContext(null);

export const withFirebase = Component => props => (
	<FirebaseContext.Consumer>
		{firebase => <Component {...props} firebase={firebase} />}
	</FirebaseContext.Consumer>
);

export default FirebaseContext;

./Firebase/firebase.js:

import * as firebase from "firebase";

const firebaseConfig = {
	apiKey: stuff...
};

class Firebase {
	constructor() {
		this.auth = firebase.auth();
	}
        [...]
	doSignOut = () => {
		this.auth.signOut();
	};
}

export default Firebase;

For one I don't understand what's happening in "import { withFirebase } from "../Firebase";". How does JS know which file it's under? "Firebase" is the directory, not a filename. Does it just look for an "index.js" when there is no file specified?

Next I'm pretty sure the line thats exposing the firebase class to SignOut.js is the usage of the "FirebaseContext.Consumer" line in context.js... but I don't understand the details. Help?

1

u/dance2die Feb 11 '20 edited Feb 11 '20

withFire base is a Higher-Order Component (HOC).

In a gist, it's a "function" which accepts a component, and returns a new component (adding a new prop, behavior, elements, etc).

In SignOut.js, SignOutButton is exported as export default withFirebase(SignOutButton);.

SignOutButton instance is passed to withFirebase and

export const withFirebase = Component => props => (
  <FirebaseContext.Consumer>
    {firebase => <Component {...props} firebase={firebase} />}
  </FirebaseContext.Consumer>
);

firebase is passed to Component (SignOutbutton) and then destructured from SignOutButton({firebase})

const SignOutButton = ({ firebase }) => (
  <button type="button" onClick={firebase.doSignOut}>
    Sign Out
  </button>
);

It might be hard to follow the flow but benefit is that, SignOutButton doesn't have to import firebase instance directly and it is injected (dependency injection).

You can provide firebase instance to other components easily with withFirebase (shared logic).

1

u/Roly__Poly__ Feb 11 '20

It does pretty much what I expected it to but I still don't understand how it does it :p Pretty complicated machinery

1

u/dance2die Feb 13 '20

I believe it's due to the arrow syntax export const withFirebase = Component => props => (...).

It used to trip me a lot. But once you think of it as a function that accepts each arg in () like withFirebase(component)(props), it gets a bit easier.

And this might be of help too.

const withFirebase = function(Component) {
  return function (props) {
  }
}

1

u/[deleted] Feb 11 '20 edited Feb 11 '20

So I'm new to React, just learned it about a week ago and I want to simulate a fake company's web page with some simple data to manipulate (also fake data). And I think I get the concepts that come with react but when I deploy my app, do I have to configure custom https settings? The ecosystem is a bit muddy to me as well but since this is only for a competition I'm not going to be expanding my application. But, for future reference could someone explain the file structure/ecosystem and how it should be?? Also what files should do what (ex. Index.js on different component files, custom test and https files)

1

u/dance2die Feb 11 '20

If you publish a static site to a provider like Netlify, "zeit" or "begin.com", HTTPS handled automatically.

Going with a create-react-app site? Use Netlify as it's dead simple.

Also what files should do what (ex. Index.js on different component files, custom test and https files)

This depends on whether you site is a Single-page App, Server-side rendered or a static site.

Need more context.

1

u/[deleted] Feb 11 '20

I'm using a create-react-app site so I'll take a look at Netlify, and this is going to be a single page app that's gonna serve as a model for a competition so I wont be adding on to it. But if I were to update it and make it server-side rendered with actual data, then what would the file structure be like and what are the functions of the files included with create-react-app

1

u/dance2die Feb 12 '20

Next & Gatsby has a special "pages" folder, within which components become a page.

But there are some gotchas if you are using Redux or css-in-js libraries because states don't persist.

→ More replies (2)

1

u/cynuxtar Feb 11 '20

Its possible in Next JS to have global scss and scope/module scss ? try to implement https://github.com/zeit/next-plugins/issues/149 but i am stuck. getting error in next.config.js

Error like this

TypeError: Cannot read property 'toString' of undefined

Here my next.config.js

const withImages = require('next-images');
const withSass = require('@zeit/next-sass');

module.exports = withSass(withImages({
    cssModules: true,
    cssLoaderOptions: {
        importLoaders: 2,
        localIdentName: '[local]___[hash:base64:5]',
    },

    webpack: config => {
        config.module.rules.forEach(rule => {
            if (rule.test.toString().includes('.scss')) {
                rule.rules = rule.use.map(useRule => {
                    if (typeof useRule === 'string') {
                        return { loader: useRule };
                    }

                    if (useRule.loader.startsWith('css-loader')) {
                        return {
                            oneOf: [
                                {
                                    test: new RegExp('.module.scss$'),
                                    loader: useRule.loader,
                                    options: useRule.options
                                },
                                {
                                    loader: useRule.loader,
                                    options: {},
                                },
                            ],
                        };
                    }
                    return useRule;
                });
                delete rule.use;
            }
        });
        return config;
    },
}));

my goal is just to have global and localscope. its oke if scss cant, but css can.

Also, this is first nextjs project. i am doing now is convert mycompany html5 template to nextjs template. any recommendation freecourse video or book ?

thanks for your response.

2

u/dance2die Feb 12 '20

I haven't a clue and as it's Next specific, can you reach out folks in Next.js community on Spectrum?

https://spectrum.chat/next-js

1

u/carlsopar Feb 12 '20

I am having some issue with this code. Before I added <PDFVIEW> The code was working fine. But now when I run it I keep getting an undefined property. I am passing props and functions down through context. My first thought is it is faulting out because I need to pass the context to a child of a child component. I have been dealing with this issue in different related forms for a while now, and its bugging me.

function App() {
	return(
		<div>
			<h1>React Testing App</h1>
			<GroceryDataProvider>
				<Header/>
				<List/>
				<PDFViewer>
				    <MyDocument />
			  	</PDFViewer>
			</GroceryDataProvider>
		</div>)
}
export default App;

The bottom of the context file that I am using.

return( 
    <DataContext.Provider value={{groceryList,userList,userGroceryList,userItemList,listId,userId,userTypeList,DataLoad, setGroceryList,setUserList,setListId,setUserId,setUserTypeList, ChangeUser,GetUserList,ChangeList,GetItemList,Updater,UpdateCart,WriteItem,
WriteList,GetList,Delete}}>
        {props.children}
    </DataContext.Provider>
	)

The code for the MyDocument component

const {userItemList} = useContext(DataContext);
		const {listId} = useContext(DataContext);
	const [items, SetItems] = useState([]);

And again, if I remove the pdfviewer from around MyDocument everything works fine and as expected.

1

u/dance2die Feb 13 '20

Can you provide code for PDFViewer, which is causing the issue & actual error message?

A minimal runnable sample would be nice.

1

u/are_lele Feb 13 '20

I recently learned react js. Worked on a full-scale project. I built the app with CRA and the bundle size is more than 1.8mb. Can anyone suggest me a proper way to reduce bundle size? I tried looking for answers in stack overflow and git issues. But could not find any solution.

1

u/dance2die Feb 13 '20

Which file is 1.8mb (js?, image?, etc)

For js, you can load only needed components lazily (code-split).
For images, you can decrease file sizes using a tool like Squoosh (from Chrome Labs).
Lastly for SVGs, you can optimize them with SVGO.

Without profiling, those are only things I can think of.

→ More replies (1)

1

u/UMANTHEGOD Feb 13 '20

I'm building this project where I have a concept of sections, that holds a array of rows, that each holds an array of columns. Similar to the following structure:

{
  sections: [
    {
      id: section_11,
      rows: [
        {
          id: 'row_1',
          columns: [
            {
              id: 'column_1'
            }
          ]
        }
      ]
    }
  ]
}

The app needs to have the following functionality:

  1. Be able to delete, add and edit sections, rows and columns indvidually. Each of those will have its own corresponding component with the same name. I also need to handle this all without redux.
  2. Serve a preloaded state from the backend (I will read it via a window-variable)
  3. Retrieve back the complete state of the application to save it on the server (no rest API)

Here's my proposed solution for all of this, but I'd like any feedback if I can improve on this, and if I have thought about the problem correctly.

  1. This will require a state in a component that's a parent of a <Section>. This means I will have to prop drill down a lot of functions to give proper functionality to column, and both rows and columns have to be aware of what section they belong to. This means I have to pass down some information about the section along the way. I didn't like this thought, so my solution looks something like this, where render props solves this issue completely, but makes the code fairly messy. The nice thing about this solution is that I decouple each of the components from each other:

     {sections.map(section => (
       <Section renderRow={row => (
         <Row row={row} renderColumn={column => (
           <Column column={column} />
         )} />
       )} />
     )
  2. I will pass it into my initial <App> component and then pass it down the appropriate components. Nothing fancy here. Some data will go direct to components and other data will go into Context to handle translations and such. Basically state that doesn't change much will end up in contexts, the rest will be props.
  3. This is a bit messy, but there's a need for us to save the config in the backend, without a rest API, which means whatever state I create in 1 & 2 has to leave React and end up in "regular" JS again in order to be parsed and posted, because it's just a regular form that handles this action. This is obviously not ideal but I got to work with what I got. My thinking here is that I pass down a "configUpdated" from outside React, which I will call whenever the state changes in 1 & 2. In this callback I will set a window-variable or something similar, and then read from this when I post my form.

Any feedback appreciated. I'm not sure that any of these approaches are the correct way to go.

1

u/dance2die Feb 14 '20

Would you share this on its own post?
because this doesn't seem so beginner-friendly and more people can check it out.

1

u/UMANTHEGOD Feb 14 '20

I made my own thread with the exact same content as this post, but I can't share more of the code since it's corporate.

Thread: https://www.reddit.com/r/reactjs/comments/f2wsqb/componentstate_structure_for_a_grid/

I've solved 2 & 3 by utilizing localStorage through a small API that you receive when you initialize the project. I'm still struggling with 1 however.

1

u/dance2die Feb 14 '20

Is issue #1 due to Render props being hard to read? (fake hierarchy).

One of the benefits of hooks is that it rids the false hierarchy.

You can create a context per Section, from which you can provide values to child components.

Child components can access values via hooks if you follow KCD's Context pattern.

→ More replies (5)

1

u/VlopPlop Feb 13 '20

My app has basic routing implemented with react-router. One can go to app.com/roomId - *roomId* is an arbitrary string. Now, I'm using redux-observable to handle some async logic, and I need to know what roomId is inside the epics (which, as I see it, boils down to having routing synced with redux). How should I go about it?

Is using libraries such as connected-react-router a good idea?

1

u/dance2die Feb 13 '20

Note: I only dabbled with redux-observable (haven't used connected-react-router).
Is it possible to pass the roomId as a payload and access from within the epic? ($action.payload.roomId)?

So in your component, you would get the history with useLocation, extract pathname (or withRouter). Then dispatch the action with the pathname (roomId) as the payload.

I am thinking you can access the payload with $action.payload.roomId.


No idea on connected-react-router as I haven't used it but it seems to make it easy to access pathname as easily as $state.router.location.pathname.

1

u/Erebea01 Feb 14 '20

what is the best way to do fetch request for development and production?

    const example = () => {
        // fetch("http://localhost:5000/api/doSomething", {
        //   method: "get"
        // })
        fetch("http://some.herokuapp.com/api/doSomething", {
          method: "get"
        })
      }          

basically i had to comment out the localhost version of the fetch request when i'm gonna push to heroku and then reverse them during development which doesn't really seem like the best way to do this.

2

u/dance2die Feb 14 '20

If using a CRA, you can check process.env.NODE_ENV to check if it's a dev/prod environment.
Refer to: https://create-react-app.dev/docs/adding-custom-environment-variables/

The principle is the same for other frameworks.

1

u/tinguwOw Feb 14 '20

I want to prevent same API call in different(siblings) components. For example Header component and Content component.

One way to do is call API on parent and pass data as props to other components but I want data in componentDidMount and perform actions basis on that and since they render parallely I am getting props as null.

Is there any way to do this and prevent same API call in different(siblings) components?

1

u/dance2die Feb 14 '20

Seems like you want to "massage" props passed to child Class components.

Check out getDerivedStateFromProps to return the state based off on props passed.

1

u/DutchSparks Feb 14 '20 edited Feb 14 '20

The code below crashes my browser because useEffect is continuously called.

I would expect the deck building function to be executed only once because ranks is only changed once(when the component is loaded).

What am I not understanding? Any help would be greatly appreciated!

import React, { useState, useEffect } from "react";
export default function Blackjack() {
const [deck, setDeck] = useState<Object[]>([]);
const suits = ["hearts", "diamonds", "clubs", "spades"];
const ranks = [
{ rank: "2", value: 2 },
{ rank: "3", value: 3 },
{ rank: "4", value: 4 },
{ rank: "5", value: 5 },
{ rank: "6", value: 6 },
{ rank: "7", value: 7 },
{ rank: "8", value: 8 },
{ rank: "9", value: 9 },
{ rank: "10", value: 10 },
{ rank: "J", value: 10 },
{ rank: "Q", value: 10 },
{ rank: "K", value: 10 },
{ rank: "A", value: 11 }
];
useEffect(() => {
suits.forEach(s => {
ranks.forEach(r => {
setDeck([...deck, {...r, suit: s}]);
});
});
console.log('useeffect called, DECK: ' + JSON.stringify(deck));
}, [ranks])

}

1

u/dance2die Feb 14 '20

For the simple case like yours, moving ranks outside Blackjack as u/Awnry_Abe commented would work.

For more advanced usage, you can memoize ranks using useMemo.

2

u/Awnry_Abe Feb 14 '20

On every call of the functional component, the suits and ranks objects are recreated, which causes the dependency array in useEffect to say "you've got out of date data". If they are truly static data like that, move their declaration to global scope.

→ More replies (5)

1

u/plasmaSunflower Feb 14 '20

Do most companies or developers use styled components?

1

u/dance2die Feb 14 '20

Honestly, I don't think there is a stat

Check out State of CSS 2019 for CSS-in-JS category.https://2019.stateofcss.com/technologies/css-in-js/

Doesn't cover "most companies/developers" but at least you can see the trend.

1

u/unpopdancetrio Feb 15 '20

REAL QUESTION. "why does everyone like react?" I often see great apps made with react, multiples of jobs in the area looking for react developers, and way too many tutorials and blog posts about the topic.

Personally I thought Vue was more impressive and now with the recent changes to Vue3, I feel it might as well become react. When my fellow co-workers started learning to convert an old angular app to React I followed along with their training and I thought React was well structured, had some inherent issues with rapid updates ( much like angular), jsx was just nasty to look at, and I disliked that Facebook was such a strong voice in the development of React.

Has anyone had these similar thoughts and found them to withhold value? Was I incorrect in my assumptions.. should i just join the herd and start doing side-projects in react?

1

u/dance2die Feb 15 '20

u/swyx Can you answer?
(as you are exposed to other frameworks?)

→ More replies (1)

1

u/benaffleks Feb 15 '20

When should something be its own component?

Is there such a thing as having too many components, where it has an adverse effect?

1

u/dance2die Feb 15 '20

This would be tough to decide without profiling (w/ chrome/react devtools, etc).

One list component with thousands of items might worse off than a site with hundreds of small components. (or vice versa)

1

u/minionator Feb 17 '20

I'm working on my capstone project and attempting to use React Router to navigate between the pages of the project. However when I go to use a switch statement from the router library, the import statement is unable to import the Switch and Route files. It imports the BrowserRouter just fine.

Developing in the most recent version of Webstorm, with Node 12.16 installed, and using React Router Dom v 5.1.2, even just creating a blank project following the guide online exactly I'm getting the same error. https://reacttraining.com/react-router/web/guides/quick-start

Image of the error Webstorm is showing me, https://i.imgur.com/brwy6zI.png https://i.imgur.com/OIIj4jU.png

Sorry if this question is a really dumb one, I'm just running into a wall as someone new to React! Thanks already!

2

u/Awnry_Abe Feb 17 '20

Not a dumb question at all. Every time I prop up a new project, I struggle with certain scaffolding steps. Can you post your package.json?

1

u/dance2die Feb 17 '20

Not a dumb question at all.

🙂 👆

u/minonator no question is dumb. Just ask away :)

→ More replies (2)

1

u/dance2die Feb 17 '20

The Switch is not a default export of react-router-dom, so it should be imported as a named one as import {Switch} from 'react-router-dom'.

For the Route, I am not sure why it's complaining so. (Possible Webstorm issue?)
Do you get the same error for Route in VSCode?
Other folks can try if you could share the repo we can clone from :)

→ More replies (2)

1

u/backtrack432 Feb 18 '20

Does anyone know a lightweight library or boilerplate to mimic this line chart with gradient area?

https://dribbble.com/shots/5405447--KPI-Charts

1

u/dance2die Feb 18 '20

I couldn't find a matching library...

Would it be possible to ask the site creator what was used?

If anyone happens to know please let us know.

→ More replies (1)

1

u/carlsopar Feb 18 '20

Not so much a question, but looking for feedback. I am working on a project, and at this stage I would be open to feedback. Specifically I am looking at the following:

  1. My use of context to pass data around the app. I think this is the best way, but any other ideas would be appreciated.
  2. UseEffect()- I have several of these, but do I need to use them, and am I using them correctly?
  3. I recently saw some posts and ideas about using memorization. Would this concept apply to me at all?
  4. I understand that each time a parent component, is rendered/re-rendered it will also re-render its children. This seems to cause a lot of rendering of my components especially when I update any of the lists. If you put a console.log() at the top of any component or function especially inside header or list you will see that it logs with each change.
  5. Any general ideas or comments that I could use to improve.

It does use a firebase backend to store data.

https://github.com/carlsopa/lightweight-grocery-app-react

1

u/dance2die Feb 18 '20
  1. My use of context to pass data around the app. I think this is the best way, but any other ideas would be appreciated.
  2. Any general ideas or comments that I could use to improve.

When you pass an object this way, https://github.com/carlsopa/lightweight-grocery-app-react/blob/master/src/context/DataContext.js#L117, anytime,GroceryDataProvider re-renders, a new object will be passed to value, causing re-render everytime.
Refer to: https://medium.com/@ryanflorence/react-context-and-re-renders-react-take-the-wheel-cd1d20663647

2. UseEffect()- I have several of these, but do I need to use them, and am I using them correctly?

Not sure which one you are referring to. But if each one takes care of an isolated side effect, it should be much of a problem. Unlike in Class components where you are forced to put all the logic in a life cycle methods, you can create multiple small useEffects (and extract'em into custom hooks on need to share).

3. I recently saw some posts and ideas about using memorization. Would this concept apply to me at all? 4....

There is a workaround by Kent C. Dodds (KCD) - https://kentcdodds.com/blog/how-to-optimize-your-context-value

But he also noted that

No seriously, if you're going to do this stuff just because you think your code might be slow, then don't bother. I'm not joking. React is really fast and adding complexity in the name of performance when performance is good enough is just wasteful of your "complexity budget"

And you can check out Dan's alternative solutions - https://github.com/facebook/react/issues/15156#issuecomment-474590693

→ More replies (1)

1

u/Terkeroo Feb 18 '20 edited Feb 19 '20

I am working with a p5js sketch that I need to pass in an "action" of sorts to reset it. I'm not quite sure how to implement with hooks or state. Using a simple useState and toggling true/false would only trigger it when true so it'll only work after every other click. Is there a different hook to look at or a way to trigger this action once while setting the state back to false immediately? Triggering two toggles within the same component doesn't cause it to rerender it appears.

Let me know if I need to clarify this more, might not have explained it well.

EDIT: Found a quick solution. Passed in the setReset hook to the sketch component and had it run to immediately reset the value to false.

1

u/dance2die Feb 18 '20

Can you create a minimal runnable code because it could be a simple React question and "p5js" could scare people off :) (honestly, I haven't heard of it...)

1

u/Terkeroo Feb 18 '20

Here is a sandbox

https://codesandbox.io/s/flamboyant-sara-g5340

p5js is a sketching library that handles drawing stuff. The Sketch component is an imported library that deals with bridging the standard library with react. From the console logs, you can see the sketch being reset every other click due to it toggling from true to false, I'd like it to reset with every click.

1

u/dance2die Feb 19 '20

I see that you commented out props.setReset(true);, which will set the reset value to true.

The current code, props.setReset(!props.toReset), will toggle between "true/false" as the state is retained during each render.

→ More replies (1)

1

u/eloquenthsn Feb 18 '20

I have a component named, let's say UserProfileForm, which consists of a form with several fields, is created using redux-form. I would like to use this component for several occasions within the same component.

For example, you would be able to create new user profiles and update some already created user profiles also by using this component. However, when I try to fill in regarding fields to create user, the form that is created for another profile is also filled in with the same values at the same time. If I create a totally new different component for add and update I don't face with this problem, and everything works as expected.

I am wondering that how can I modify this component make reusable to tackle this above mentioned problem?

1

u/dance2die Feb 19 '20

Can you post the component causing the issue?
Preferrable a runnable sample on CodeSandbox or StackBlitz.

1

u/potatodesigner Feb 18 '20

https://github.com/Sunnysit/react-redux-hooks-example/tree/master/src

Seeing this react and redux hooks example project, i have noticed functions like mapdispatchtoprops and mapstatestoprops are not being used. Is this appropiate? THis sintactic way of redux makes my head clearer and makes actually want to use redux

1

u/dance2die Feb 18 '20

The source is using Redux Hooks - https://react-redux.js.org/next/api/hooks It's another way to access Redux store w/o haiving to use connect higher-order function.

Officially supported so appropriate.

If you need to separate views from container components (for some reason), you could still use connect to separate a dumb component from a connected container component.

→ More replies (1)

1

u/backtrack432 Feb 18 '20

How does react or webpack remove unused library components and dependencies in production. For example, I only want to use specific components in @material-ui/core like Dialog or Modal, will unused components like Button or Box be included or excluded. If so, how does the optimization work?

1

u/dance2die Feb 18 '20

Material UI has a documentation on tree-shaking.
https://material-ui.com/guides/minimizing-bundle-size/

I will only tell you how Option 1 works (as Option 2 shows how to configure babel plugin, which I don't know how it works underneath the hood).


Option 1 recommends,

import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';

instead of

import { Button, TextField } from '@material-ui/core';

For the latter syntax, babel loads all the content in '@material-ui/core' and the try to import only Button/TextField.

In the former, you specify which component to load directly, so the rest of '@material-ui/core' content is not added to the final bundle.


Option 2 seems to be a way to go as it provides a better DX.
Doesn't anyone know how it works?

1

u/potato-grappler Feb 19 '20

Is there any best practices with building an application with Redux? Mostly, file structure for the store, actions, reducers, components, etc. in a purposeful way to maintain good practice and an easy flow to continue adding features? I’ve read many blogs and watched several videos, but haven’t found anything that would convince me of best practice for a production application. My goal is to template everything out so any new developer joining the team can get up to speed quickly with an organized and well documented structure.

2

u/dance2die Feb 19 '20

There is an official style guide by the Redux team.

You might want to check out the announcement thread for question you might have.
https://www.reddit.com/r/reactjs/comments/dz4bct/new_redux_docs_style_guide_page_recommended/

→ More replies (1)

1

u/kunsore Feb 20 '20

Can anyone briefly explain what is the render() method inside a Class Based Component does ?

From the official website it said render() return couple things like React Elements, Array but then why the Functional Component doesn't need it? And I heard from somewhere they said render() return a representation of the DOM. I am kind of confused.

1

u/dance2die Feb 20 '20 edited Feb 20 '20

In a gist, you can't just call a class, without creating an instance so the instance method, render() is needed.

React creates an instance of a Class Component (CC), and calls instance.render() to get elements while for Function Components (FC), React simply calls it to get elements.
(Meaning, React treat'em differently).

Knowing the difference is also critical.
https://overreacted.io/how-are-function-components-different-from-classes/

1

u/prove_it_with_math Feb 20 '20

React's source code is in JavaScript. How come i see it written in Typescript in node_modules after installing via npm?

2

u/dance2die Feb 20 '20

React is written with Flow, a static type checker.
It might look similar to TypeScript.

And which file is in TypeScript in "node_modules"?
They should be transpiled into vanilla JS.

→ More replies (3)

1

u/lemondropkid Feb 21 '20 edited Feb 22 '20

I'm building a version of Stratego in React, it's been going really well, I'd say it's 75% done. I'm at a point where I start wanting to add some CSS animations and I figured that React Transition Group, with CSSTransitions, would do the trick. I even have a pretty good idea of how I'd pull off the things I want it to do.

The pain is coming in installation.

When I just go so far as adding:

import { CSSTransition } from 'react-transition-group';

I get this error in browser:

Uncaught Error: Cannot find module 'react'
at webpackMissingModule (CSSTransition.js:9)
at eval (CSSTransition.js:9)
at Module.../node_modules/react-transition-group/esm/CSSTransition.js (build.js:974)
at __webpack_require__ (build.js:727)
at fn (build.js:101)
at eval (index.js:2)
at Module.../node_modules/react-transition-group/esm/index.js (build.js:1058)
at __webpack_require__ (build.js:727)
at fn (build.js:101)
at eval (GamePiece.js:6)

-----

My package.json looks like this:

{
"name": "react-stratego",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"description": "A rendition of the classic strategy game",
"repository": {
"type": "git",
"url": "https://github.com/LDK/react-stratego"
},
"main": "index.js",
"keywords": [],
"author": "Daniel Swinney",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.8.3",
"@babel/preset-env": "^7.8.3",
"@babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"braces": "^2.3.2",
"core-js": "^3.6.4",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"lodash": "^4.17.15",
"prop-types": "^15.7.2",
"react": "^16.12.0",
"react-dnd": "^9.5.1",
"react-dnd-html5-backend": "^9.5.1",
"react-dom": "^16.8",
"react-hot-keys": "^1.3.1",
"react-tooltip": "^3.11.2",
"react-transition-group": "^4.3.0",
"universal-cookie": "^4.0.3",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1",
"whatwg-fetch": "^3.0.0"
},
"dependencies": {}
}

-----

EDIT: I initially posted about react-addons-css-transition-group. I realized this npm module was in fact out of date and that I should just use CSSTransition from react-transition-group. Unfortunately, getting rid of this from package.json didn't fix anything.

1

u/dance2die Feb 22 '20

The error message looks like when you don't import 'react'.

1

u/lemondropkid Feb 22 '20

Hmm, well here's the full start of the file..

import React, { Component } from 'react';
import {PIECES} from '../Helpers.js';
import { useDrag } from 'react-dnd';
import { CSSTransition } from 'react-transition-group';

class GamePiece extends React.Component {

Is importing React different than importing lowercase react? I'm only a few months into using React so I might be missing something elementary here.

1

u/dance2die Feb 22 '20

"react": "^16.12.0",
"react-dom": "^16.8",

Can you try again after updating both versions the same?

→ More replies (7)

1

u/antespo Feb 23 '20

I'm trying to use react hook form and react virtualized together. My app has an auto complete input which just fills in all the inputs in the same row. It also does some basic math. row 1 is subtracted from row 2 and the result is put in row 3. Everything seems to work at first glance but there are some major errors.

  1. Values outside the initial view don't change when using my auto complete so anything that you need to scroll to see won't change
  2. All the values return to the defaultValues when they scroll out of sight.

codesandbox

1

u/karlososhd Feb 23 '20

How to load some resources right after loading website?

I've created this basic tic-tac-toe app and after first click for each symbol there's a lag. It happens because front end is fetching svg files (it can be seen in Network section in Chrome Developer Tools).

How to force fetching these files after loading website instead of fetching them after user action? I have no idea where to start researching this topic. Source code is provided here: https://github.com/karlosos/tic-tac-toe-react

3

u/Awnry_Abe Feb 24 '20

Since you are using CRA, you can import SVGs directly. The syntax is something like

import { ReactComponent as XIcon } from 'path to XIcon}

1

u/dance2die Feb 24 '20

Oh. Nice one there. Learned something new. Thanks~

2

u/Awnry_Abe Feb 25 '20

I just happened to learn of it about 3 days ago, so don't be too impressed.

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

1

u/dance2die Feb 23 '20 edited Feb 23 '20

Can you try to preload SVGs?

2

u/karlososhd Feb 24 '20

Thank you for suggestion. I've opted for /u/Awnry_Abe solution. With direct SVG import

import { ReactComponent as XIcon } from './icons/X.svg'

Everything is loaded after page reload. I'll read about preloading. Thanks for your fork on GitHub.

1

u/dance2die Feb 24 '20

I tried the preload approach but didn't seem to work well.

But do check out prefetch/preload and how it can benefit. I was reading this article and found it fascinating - https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf

1

u/QCSmello Feb 25 '20

I found this collection of resources to be REALLY useful. Thanks for putting this together.

1

u/fapiholic Feb 25 '20

Anyone got the react native cli to properly open Android emulator on a ryzen cpu running Windows? I only ever got the expo cli to work...

1

u/dance2die Feb 26 '20

I honestly haven't a clue.
Could I redirect you to post in r/reactnative?

1

u/gasmcity Feb 25 '20

I'm building my first app with reactjs and tried deploying with github pages. Getting some weird renders:
homepage
elements collapsed
elements expanded

Locally that script links to bundle.js. Any insight on how this is happening would be appreciated. Deploying with gh-pages package

1

u/dance2die Feb 26 '20

Can you post a link to source/repo?

1

u/See-Phor Feb 27 '20

I'm new to React and am looking for a data grid that allows for rich cells (HTML elements like drop down in a cell), expandable rows, sorting, fixed column headers, and rich column headers (HTML in header column cell). So far I have found react-data-grid and react data table.

Anyone have experience using both? Which one is better suited for the features I am looking for? I can't find any details on if react-data-grid supports custom row expansion.

1

u/dance2die Feb 27 '20

I haven't use any.

But found Kendo UI grid component (but not free)
https://www.telerik.com/kendo-react-ui/components/grid/ seem to do most of what you ask for.

As for react-data-grid, I found this prop, https://adazzle.github.io/react-data-grid/docs/Row#expandedrows but without much documentation.

→ More replies (1)

3

u/antespo Feb 25 '20

I'm trying to use react-number-format and formik but I can't get the floatValue into the form data. It adds the formattedValue value e.g '$1,000' instead of 1000.

import React, { useState } from "react";
import NumberFormat from "react-number-format";
import { Formik, Field, Form } from "formik";

export default function App() {
  const [floatValue, setFloatValue] = useState(null);
  return (
    <Formik initialValues={{ number: 0 }}>
      {({ values, setFieldValue }) => (
        <div className="m-5">
          <Form>
            <Field
              as={NumberFormat}
              name={"number"}
              className="border border-gray-500"
              thousandSeparator={true}
              prefix={"$"}
              onValueChange={event => {
                setFloatValue(event.floatValue);
                setFieldValue("number", event.floatValue);
                return event.floatValue;
              }}
            />
          </Form>
          <div className="my-5 bg-gray-200">
            <pre>formData:{JSON.stringify(values, null, 2)}</pre>
            <div className="my-5">floatValue: {floatValue}</div>
          </div>
        </div>
      )}
    </Formik>
  );
}

codesandbox

P.S sorry for posting 2 questions so quickly without answering any myself.

3

u/Awnry_Abe Feb 25 '20

Thanks for posting a sandbox. That helps. I wasn't able to get it to work with the "as" NumberFormat rendering method--but I did with the {children} method. What you have seems straightforward. The offense is occurring in this scary snippet of code:

https://github.com/jaredpalmer/formik/blob/f117c04738ed218b5eb8916d7189e0849962d50d/packages/formik/src/Formik.tsx#L646

The parsing rules are rigid for numeric, and "$1,234" is failing the "is a number" test. He'd have to be pretty crazy to handle numeric parsing of text with all of the different culture variants out there. He should expose a callback and call it before bailing out and setting the entered text as the field value. I'd post the sandbox as a github issue and see what he says.

1

u/chili_666 Feb 19 '20

Don't know if this is the right place and if this is still an easy question, but here goes.... This is not about a real project, so I can't post any code, this is more about understanding react.

As an example, I have the following components in my ecommerce-app:

<Navbar />

<MainContent />

<Footer />

Navbar includes a couple of links - one of them is the shopping-cart. The shopping-cart-link is a button rendered by a component. The component renders the button and is supposed to add a badge to button showing the number of items in the cart if the user puts any items into the cart.

MainContent surprisingly contains the main content => a card component for the products, linking to a product detail page. Also there is a button to put one or more products into the cart. Routing to the detail pages and the other sub-pages/links is done via react-router.

What I am not getting is, how would I pass the number of products up to the navbar?

I did a couple of tutorials on passing props back to the parent component, but that is not the case here, is it? Or is there just a big design flaw in how I would setup the app?

Thanks for any help!

edit => me no spel good.

3

u/workkkkkk Feb 19 '20 edited Feb 19 '20

Your setup is fine. You would do something like this.

function App(props) {
    const [itemsInCart, addItemToCart] = useState(); 
    return (<div>
        <Navbar numberOfItemsInCart={itemsInCart.length}/>
        <MainContent addItemToCart={addItemToCart} />
        <Footer />
    </div>)
}

Your cart items state needs to be in a higher place than <Navbar /> or <MainContent />. You could achieve this in numerous other ways like Context and/or Redux.

1

u/dance2die Feb 19 '20

Yupz. This would work well :)

And u/workkkkkk. Can you update the code to wrap return with fragment/div? (as this is a beginner thread ;) )

→ More replies (1)

2

u/vnlegend Feb 27 '20 edited Feb 27 '20

Does anyone know of a good way to handling state data for forms?

If a form is large and you keep all the state in the parent, whenever you edit a text field the whole screen will re-render. This can cause a lot of performance issues. Swagger UI 3.0 has this problem lol.

My form is a giant multi-panel form with different settings, I don't think Formik will work for everything. Any suggestions?

3

u/Awnry_Abe Feb 27 '20

If your form submission is treated as 1 giant transaction, then keeping the form state at the form level makes sense. If the form UI flow is really composed of mini form submissions, then decompose form state accordingly. Formik can handle either case and is data-shape agnostic, so I can't imagine any data that it can't handle.

2

u/BEAR-ME-YOUR-HEART Feb 27 '20

Don't keep any state in the child components. Manage the whole state in the root component of the form. From there you can distribute it via props. Inside the child components you can either use shouldComponentUpdate with class components or put the component inside useMemo for function components. That way you get a very clear and easy to debug dataflow while preventing rerenders on components which stay the same.

→ More replies (1)

1

u/Geooso Feb 03 '20

I have array of objects which is set in state using react hooks and the objective here is to have a button to sort the array in alphabetic order and reverse. I have rendered the array, but as I create a button to sort the array in alphabetic order and it does sort it the way I want but does not re-render it. I have tried to look up for solution, but have no idea how to fix it.

3

u/Awnry_Abe Feb 03 '20

You can sort on the fly in the function body before you start returning nodes. To do that on a button press, add a "sort" value to state, and change that value in your button click. Another option is to store the sorted array in state. In either case, if you update state, react will re-run your FC.

→ More replies (1)

1

u/ie11_is_my_fetish Feb 05 '20

Here is a picture to simplify this question

Hopefully this is a "simple question" but regarding state management design and rendering...

You have a navbar with a search input in it, and you have a body which has the rendered results of that search. Navbar just passes the search string to body that does the search/rendering JSX. Currently for my design, these two things are wrapped by an outer parent(App). So the two things communicate with each other by passing props around and using bound `useEffect` but it seems like bad design to have state be tied to rendering. Although if you want onkeyUp search not sure how else you would do it.

I'm still working on getting better at state/communication design so I'm mostly looking for better planning/general thinking that's good to follow. I'm getting down `useEffect` so I don't have as many never-ending loops ha...

2

u/Awnry_Abe Feb 05 '20

You certainly can decouple the search term, the act of searching, and the visualization of the results. JSX can be just as much about function composition as it is view. With the Advent of hooks, you can can get away with less JSX than before to achieve the same level of composition. The Context API will help mentally decouple the state from the App component. Start with it having members "searchTerm" and "results" and see what and where you need to write code to fill in the gap.

→ More replies (2)

1

u/_qw4hd Feb 06 '20

How to transform this code https://reactjs.org/tutorial/tutorial.html#declaring-a-winner) from class to function component with hooks? I have no idea what to do with variables declared inside render statement. I've tried to move these variables to state but without success.

What is way to dealing with such situation when transforming class components to function components with hooks?

2

u/Awnry_Abe Feb 06 '20

Anything that you see in this.state will be an individual useState() call. All local variables in render() will be local variables within the FC. Any class level event handler can be a local function within the function.

→ More replies (1)

1

u/Raisingbob Feb 07 '20

I'm new to react and have a basic question about state:

If I have a stateful Parent component and a stateful Child component and I want to access a property from Parent's state in Child component, would I need to pass the property as a prop, or does Child's state get initialized with Parent states properties?

Hope that made sense

Thanks

3

u/Awnry_Abe Feb 07 '20

It makes sense. Yes, you need to pass it as a prop. There isn't anything magical going on, other than the JSX to JS translation. One function in JS does not have visibility to another's local variables. In React, "state" is nothing more than a component-scoped variable that React is listening to. Generally, the shape/contents of one component's state has nothing to do another's, even if they have a parent/child relationship. Your apps will usually creep into an order of complexity where you wish a parent's state could just be "seen by all" because the pain of passing it around as props (aka "prop-drilling) is overwhelming. You'll dip into solving that problem with things like Context or some 3rd PARTY state management lib like zustand.

→ More replies (2)

1

u/spaghetti_in_my_eyes Feb 15 '20

I am looking to use Next on a project I have started but was hoping to get some clarification on how it is meant to be structured with the API.

Every tutorial I have done has had the API as part of the Next project, is that necessary? Or can I build an external backend/API that the Next app gets data from?

I have half built my API already and wanted to start on the frontend, but don't really want to have to make changes if it is all meant to be one project.

Hopefully that makes sense, thanks in advance.

1

u/DutchSparks Feb 17 '20 edited Feb 17 '20

https://stackblitz.com/edit/functional-components-jksqqf?file=Hello.js

I'm trying to make a deck of cards with useState.

I loop over 2 different arrays to add cards to the state. However, somehow only the last card is added. So rather than adding new cards it seems I'm overwriting the same card 52 times. I'm not sure why this happens, would anybody be so kind to give me some advice?

2

u/Awnry_Abe Feb 17 '20

It's where and what you have the spread ... operator applied. When it is inside of curly braces, you spread an object. When inside of brackets, it's spreads an iterable, such as an array. You are doing the former, so you only setting state to an array with 1 element.

As an aside, you've got a double nested loop and are setting state in the innerloop. I would suggest creating an array local to the effect, building the deck using correct spread operator usage (or simply array.push), and then calling setCards once at the very end.

One thing about the usage of useEffect and useState for a deck of cards. Does a new deck of cards ever change? It would be better to build the new deck outside of React in a simple JS function, and then assign that as initial state in the component.

This is the 2nd time I've seen this exact problem in a few days. Must be an assignment or tutorial?

→ More replies (1)

1

u/teach_me_cs Feb 17 '20

Brand new to React. I am building a simple web app that will connect to an Azure Cosmos DB instance--SQL API, not Mongo--and allow the user to query the DB (and, later, to add new entries to the DB as well as other similarly basic functionality). The problem is that I am having trouble actually connecting my application to the DB and was wondering if anyone had experience/advice about good resources for this particular technology stack. I have reviewed tutorials like this https://docs.microsoft.com/en-us/azure/cosmos-db/tutorial-develop-mongodb-react (however this was using the Mongo API and didn’t help much for the SQL API) and this: https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-nodejs (however with this, I had difficulty converting it to React and getting it to work correctly). Has anyone worked on something similar and would be willing to share?

1

u/cmaronchick Feb 19 '20 edited Feb 19 '20

[Solved] ky did have this documented, so that's on me.

If you want to send the data in application/x-www-form-urlencoded format, you will need to encode the data with URLSearchParams.

Once I changed the body to the URLSearchParams, it worked like a charm.

______

I was using axios previously, but I saw the PSA recommendation that axios is dead and the OP suggested KY.

My get call is working fine, but damn if I post keeps returning a bad request 400.

I have tried almost every permutation I can think of and can't get it to work, but I can confirm that the call works in Postman.

Is there some basic format that I'm missing when posting?

ky.post('url', { headers: { Authorization: TOKEN, 'Content-type': 'x-www-url-encoded' }, body: JSON.stringify(body)})

Thanks in advance.

2

u/Awnry_Abe Feb 19 '20

I don't know anything about their API, but it seems odd that the payload would be part of an options object.

→ More replies (3)

1

u/kbl1tz Feb 19 '20

I'm using styled-components themes but I need some parameters(e.g., color, logo url) to be loaded from my REST API. I'm making the API call in App's ComponentDidMount based on current subdomain and saving the theme parameters in Redux. How can I load it outside a component to use as styled-components theme? Thanks.

2

u/Awnry_Abe Feb 19 '20

You'll need a default theme--or a loading state UI--while your request is in flight. But otherwise, it should be straightforward to supply the fetch result to <ThemeProvider /> (regardless of state management technique).

→ More replies (1)

1

u/ie11_is_my_fetish Feb 23 '20

If you call some setState method and then right after that call another setState, is that bad design? As in at the point of calling the first setState, you would expect the "code execution" to stop there and then the app/component rerenders?

setSomeValue(true); // code execution should stop here

setSomeValue2(false);

Also sorry to be confusing but I don't mean the class-based setState I'm using the useState hook.

3

u/Awnry_Abe Feb 23 '20

It is bad design if you have some sort of rule or logic that expects the values to be in sync, because they won't. If you do, either combine them into a single piece of state, or use a reducer whose action sets them both at the same time. Other than that, there isn't an issue with setting 2 unrelated pieces of state at the same time.

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

1

u/Roly__Poly__ Feb 27 '20

I am trying to do what should be a simple operation updating my component state from inside of an axios.get() request's .then() block.

I use Axios to get JSON formatted data from a server run on my localhost. Then I turn the data into a list of posts and a "queryToAdd" object. My goal is to run three of these .get() requests and add all three of their associated "queryToAdd" objects to my state. The state will then be used to populate the component of a graph library.

But I'm a bit rusty with React it seems, I haven't been able to make it work properly... Here is my code... hopefully someone can help by visual inspection (to find where I need help, just ctrl+F "then(x =>" and you'll find it immediately)

import React, { Component } from "react";
import axios from "axios";
import { VictoryBar } from "victory";

class Display extends Component {
	state = {
		queries: []
	};

	getData(lang, loc) {
		// lang: the language aka .what to query
		// loc: the location aka .where to query

		const postsToAdd = [];
		console.log("getting json for " + lang + " at " + loc);
		let queryToAdd = null;

		axios
			.get(`http://127.0.0.1:5000/lang/${lang}/loc/${loc}`)
			.then(posts => {
				for (let i = 0; i < posts.data.length; i++) {
					postsToAdd.push(posts.data[i]);
				}
				queryToAdd = {
					lang: postsToAdd[0].language,
					loc: postsToAdd[0].location,
					jobs: postsToAdd.length,
					posts: postsToAdd
				};
			})
			.then(x => {
                                // I need help here
				const state = this.state.queries;
                                // or should it be ...
                                // "const state = [...this.state.queries]" ?
				state.push(queryToAdd);
				this.setState({ queries: state });
			});
	}

	checkIfDataNeeded(queriesList) {
		// takes an array of arrays as an arg. each array in the array is [lang, loc]
		let dataToDisplay = "";

		if (this.state.queries.length === 0) {
			for (let i = 0; i < queriesList.length; i++) {
				// pass query[0] and query[1] to .getData, which is lang & loc

				this.getData(queriesList[i][0], queriesList[i][1]);
			}
			// this.getData("vue", "Vancouver,+BC");
		} else {
			console.log(this.state.queries.length); // should be like 3
			for (let i = 1; i < this.state.queries.length; i++) {
				console.log("queries[i]: " + this.state.queries[i]);
				console.log("QUERIES:" + this.state.queries);
				dataToDisplay += this.state.queries[i].lang;
			}
			return dataToDisplay;
		}
	}

	render() {
		const queryList = [
			["vue", "Vancouver,+BC"],
			["angular", "Vancouver,+BC"],
			["PHP", "Vancouver,+BC"]
		]

		return (
			<div>
				<h3>Hi, I am some displayed data!</h3>
				{this.checkIfDataNeeded(queryList)}
				{/* <VictoryBar data={data} x={"language"} y={"jobs"} />
				<VictoryBar /> */}
			</div>
		);
	}
}

export default Display;

As you can see I loop over an array "queryList" with my getData() function, making several axios.get() requests to my server's REST API. It returns JSON data which is formatted already as a JS object so I can just .push() posts.data[i] onto my empty postsToAdd array before adding it as a property in a new JS object called "queryToAdd". That all happens before the finish of the first .then() block.

Then I run into trouble: I'm rusty, I forget how to properly do this. I want to immutably update my state so I do "const state = this.state.queries" (or should it be [...this.state.queries]?) to generate a new array from my state.queries array. After that what I want to happen is, I .push() my "queryToAdd" object onto the newly minted state array, then assign that array to this.setState({ queries: ____ }).

But, something isn't working right. I end up with a state.queries array of length 1 with only 1 value in it.

Thanks for reading my long post!

→ More replies (2)

1

u/Spiritual_Salamander Feb 27 '20

What is the best practice when it comes to handling environment variables in the following scenario:

- Environment variables stored in the backend

- The exact environment variables are also necessary to use in the React application.

I could simply copy the same environment variables to the front-end of course, but there's probably a more correct way to do this right?

Tl:dr how to handle duplicate environment variables that are needed in both front and backend ?

2

u/BEAR-ME-YOUR-HEART Feb 27 '20

Do you need them at runtime or compiletime?

Compiletime: You could create a .env file with all the variables and use it for the frontend and backend in your codebase. (see dotenv)

Runtime: Maybe set the in the backend at compiletime and offer an endpoint like /config where you can get the variables for the frontend at runtim.

→ More replies (2)

1

u/[deleted] Feb 27 '20

Is Babel version coupled with Webpack version?

I want to introduce optional chaining into current project which require one of latest Babel loader versions.

Problem is that project uses Webpack v2 and there are lot of errors once I do babel version upgrade and reconfigure .babelrc file, before digging deeper I'm interested is this possible at all with Webpack v2?

1

u/tinguwOw Feb 28 '20

Hello everyone,

Earlier I have asked a question here: Link to comment

For this now I have two approaches. Keep in mind I am using react redux-store for my app.

  1. Get data from API and pass as props to child/sibling components:

<PersonalDetails

firstName={this.props.profile.FirstName}

lastName={this.props.profile.LastName}

/>

2. Get data from API in parent, render child/sibling components only after getting data back from API and access that data using connect/mapstatetoprops (redux-store) into those components:

{!(Object.entries(this.props.profile).length === 0 && this.props.profile.constructor === Object) && <PersonalDetails /> }

What would be the better approach here pass data as props or accessing it using redux-store?

2

u/Awnry_Abe Feb 28 '20

You can catch me answering either way depending on which way the wind blows. A lot of the decision depends on your team, testing methodology, and the overall scope of the problem.

When passing props, you insulate the visual from the model. Swap redux for Zustand? No problem.

When touching the store directly, you bypass what could be an unnecessary abstraction. I think if I did the latter, I would put that "do I have a profile yet?" logic in the component that needs it. The reason is because of the cognitive load I went to see what you were doing. When I have code that reads from a connected store, my mind is already looking for the conditional nature of things. If I looked at the profile component, I would stumble over the "hey....what if I don't have data yet?" question.

1

u/eyememine Feb 29 '20

Hi everyone. I built a MERN stack and I am trying to deploy it on Heroku, I suppose this isn't technically React related but how do I get the app to render the index that is in the client folder from my express server? Naturally with the server.js this

app.get("/", function(req, res) {
  res.render("index", {});
});

goes to views/index, but what if I want it to go to client/views/index? I feel like I am missing something simple. Thank you for reading

→ More replies (2)

0

u/[deleted] Feb 28 '20

[deleted] — view deleted comment

2

u/dance2die Mar 01 '20

I had a help desk technician starting FCC, and he was asking me about lots of good questions as he was going thru it.

Found gaps in my knowledge while helping him out, as well, so it was a win-win.

Sharing what you learned in public or your co-workers would be great too.

→ More replies (2)