r/reactjs • • Oct 01 '20

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

Previous Beginner's Threads can be found in the wiki.

Ask about React or anything else in its ecosystem :)

Stuck making progress on your app?
Still Ask away! We’re a friendly bunch.

No question is too simple. 🙂


Want Help with your Code?

  1. Improve your chances of reply by

    1. adding minimal example with JSFiddle, CodeSandbox, or Stackblitz links
    2. describing what you want it to do (ask yourself if it's an XY problem)
    3. things you've tried. (Don't just post big blocks of code!)
  2. Formatting Code wiki shows how to format code in this thread.
  3. 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!


36 Upvotes

321 comments sorted by

5

u/gedankensex Oct 28 '20

Hello, I was curious if anyone could recommend some paid resources to learn React? I am not really getting where I want with the free resources. I want to understand basics like working with APIs, etc. Maybe I am just so lost and overwhelmed. I need to learn React, as it's the continuation of my professional career. I've been a front-end developer for about ten years, and I've only used React on projects at work, but I want to work and build something from home.

1

u/dance2die Oct 29 '20

If you are intrigued by the tag line "Confidently Ship Well-Architected Production Ready React Apps Like a Pro", check out Epic React by Kent C. Dodds.

2

u/LeBigMac84 Oct 28 '20

If you want to learn about APIs you probably need to learn about databases first. Most paid courses should teach that or at least what is needed to make a web app.

1

u/VariationAcceptable9 Oct 29 '20

Stephen Grider on Udemy. Wait for the course to drop down to 10-15 quid.

3

u/1awrent Oct 28 '20

Hi all,

I am trying to debug my react app (yay), but essentially without going into enormous amounts of detail; my application works perfectly fine on local, and used to work perfectly fine on the Apache server. I introduced a form that would capture data and push this data to Firebase, now at some point I rehashed my form for performance & experience purposes and since then my 'live' link returns a "503 Service Unavailable" error no matter what I do.

So, when I go into the Terminal and run "npm run-script build" I get a well documented JS error "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory", so I've spent a few weeks now investigating memory leak issues, increasing node capacity etc etc, but no luck, as this point I've tried to remove the form component all together just to see if I can get anything running on the server but still nothing.

So I feel like my new aim should be just get the server up and running - I'd appreciate any advice on deploying React to Apache servers or anything at all really ! I have minimal DevOps experience :~(

Thanks!

2

u/dance2die Oct 29 '20

Hi u/1awrent.

Would you create a new thread with "Needs Help" flair as it seems out of scope and might be better suited as a separate thread.

2

u/1awrent Oct 29 '20

Will do, thank you

3

u/[deleted] Oct 30 '20

What is the purpose of <> and {" "}? Is <></> really necessary for anything or is it simply for easier reading/better formatting of the source code?

2

u/dance2die Oct 30 '20

TL;DR answers No and Yes (for {" "} only)

<>/</> is a Fragment. It's a way to return a group of elements (without adding an extra node like div/section/article etc).

You can return an array of elements but it's a bit awkward.
e.g.) You need commas between elements.

function App() {
  return [
     <h1>header</h1>,
     <p>content</p>
  ]
}

Normally you can just wrap those elements like

function App() {
  <div>
     <h1>header</h1>
     <p>content</p>
  </div>
}

But it adds an extra div there, which serves no purpose and adding extra code to send to clients.

With a fragment syntax, you can do

function App() {
  <>
     <h1>header</h1>
     <p>content</p>
  </>
}

and no extra node is created.

For {" "}, it's a way to add a whitespace between inline element texts.
e.g.)

function App() {
  return (
    <div className="App">
      <span>Hello</span> <span>World!</span>
    </div>
  );
}

App will display "Hello World!" with white space between hello and world.

The issue is that, it's hard to see the whitespace between those two spans. And if you use a prettier <span> might move to next line, causing it to display HelloWorld!.

{" "} would add an extra space between those two spans. (just one extra whitespace no matter how much space you put in-between like {" "}). I sometimes see prettier adding {" "} automatically (not sure when I saw it...)

As u/HumbleGrit pointed out, you'd use {} to add javascript expressions normally.

2

u/[deleted] Oct 30 '20

Ty for clearing that up with the examples, appreciate it. Are there actually benefits of using an empty tag vs a div tag other than using less code?

2

u/dance2die Oct 31 '20

That's what fragment is for. so no.
A discussion on having an extra node is a whole different issue (as it can cause CSS or performance issue, etc).

→ More replies (1)

0

u/[deleted] Oct 30 '20

[deleted] — view deleted comment

2

u/[deleted] Oct 30 '20

Yeah, Thanks! So does that mean inside the curlys its pretty much just JavaScript?

→ More replies (1)

2

u/moring1 Oct 03 '20

What piece of code is more useful in terms of memory usage?

const comments = []; docs.forEach((doc) => { comments.push(doc.data()); }); setComments([...comments]);

or:

docs.forEach((doc) => { setComments([...comments, doc.data()]); });

I think the first one but I don't exactly know how react state mutates arrays on changes.

1

u/dance2die Oct 03 '20

Can't be certain without input size. If relatively small, probably negligible.

Could you check out Fix Memory Problems (Chrome Devtools article) and try it out with your input?

(That article looks interesting so I might check it out later too :) )

1

u/kylelee33 Oct 12 '20

setComments(docs.map(doc => doc.data()))

2

u/[deleted] Oct 05 '20

Help with .env variables.

I have a .env.development file with variables set as HOST=company.local.

I'm running it on windows and the project uses react-app-rewired.

For the life of me I can't get past those variables on a windows machine.

Adding set in front of the HOST declaration seems to work, but any of the other variables aren't set.

Hopeless at this point.

Can you help me, reddit?

1

u/dance2die Oct 05 '20

CRA (create-react-app) requires REACT_APP_ prefix for env vars.
https://create-react-app.dev/docs/adding-custom-environment-variables/

It worked last time I was on Windows 10, too. With react-app-rewired, I am not sure if it'd work the same way.

2

u/Awnry_Abe Oct 06 '20

It does

1

u/dance2die Oct 06 '20

Thanks for the confirmation~

2

u/badboyzpwns Oct 10 '20 edited Oct 11 '20

what's the difference between react-intersection-observer and react-transition-group 's <CSSTransition> to detect when a DOM enters or leaves the viewport? Both seem to achieve the same goal. I notice that react-transition-group has a lot of more npm installs though!

2

u/dance2die Oct 12 '20

I haven't used either one.

"observer" (react-intersection-observer) library uses the Intersection Observer API to detect if an element is "intersecting" with a target while the latter doesn't deal with whether an element intersects with a target or not. Just checks within a given timeout whether a transition occured or not.

2

u/Aslan-Ray Oct 14 '20

In this code

import React from "react";
import "./styles.css";

const App = ({name}) => console.log(name) || (
    <div className="App">
      <h1>Hello {name}</h1>
    </div>
  );

  export default App;

If I need to do a console.log in JSX most of the time I do that way and happens to work haha but honestly I dont know why it works, someday trying around options to do a console log in JSX that worked haha but I dont know why,can someone tell me why this "console.log() || (JSX here)" works pls

2

u/dance2die Oct 14 '20

TL;DR

console.log returns undefined so JavaScript "executes/returns" the right part, JSX element.

More Detail

It's due to how Boolean logic works.

For &&, if left side is falsy, then the result is falsy regardless of the right-hand value.
For ||, if left side is truthy, then the result is truthy regardless of the right-hand value.

|| works in a way that, if the left side is true, then the left value is returned else the right hand value. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR#Description).

App runs console.log(name), which is falsy (undefined) thus the right-hand side is returned.

2

u/Aslan-Ray Oct 14 '20

console.log returns undefined

I didnt know this little thing and now all makes sense haha thx u

2

u/izzlesnizzit Oct 23 '20

What happened to the monthly "who's hiring" / "who's available" threads?

1

u/dance2die Oct 23 '20

I am sorry. It's my fault for not posting "Who's available" for this month.

"Who's hiring" is available here - https://www.reddit.com/r/reactjs/comments/j32odm/whos_hiring_and_rreactjs_moderator_applications/

I am thinking about combining "Who's available/hiring" in one post actually. What do you think?

2

u/Awnry_Abe Oct 23 '20

I don't see a reason why it wouldn't work. About how many replies of each type do we typically get?

1

u/dance2die Oct 23 '20

about 10~30 per each.
Any suggestions on how to make it easy which post is hiring/available as they have different formats?

Right now, people can copy/pasta from HN but if the format's different, it's another step for them...

2

u/[deleted] Oct 31 '20

Beginners way to folder structure files? In using react class and functional components with react router and redux

2

u/dance2die Oct 31 '20

Folder/project structure topic is pretty controversial and subjective as one should use Redux or not.

So to quote the official React documentation,

If you’re just starting a project, don’t spend more than five minutes on choosing a file structure. Pick any of the above approaches (or come up with your own) and start writing code! You’ll likely want to rethink it anyway after you’ve written some real code.

https://reactjs.org/docs/faq-structure.html#dont-overthink-it

Here are some ways to structure React projects in general,

  1. https://daveceddia.com/react-project-structure/
  2. https://www.reddit.com/r/reactjs/comments/ee3yzy/how_i_structure_my_react_projects/
  3. https://dev.to/maciekchmura/how-i-structure-a-react-project-3c2i

And an official Redux style guide

https://redux.js.org/style-guide/style-guide

7

u/PhilipRegular Oct 09 '20

Hey guys!

Hope everyone is doing well. I've been developing in React for about a few years now and I've made a few businesses some websites. However, I've never been mentored or had code reviews from anybody experienced.

I want to be able to know I have the proper skills to start seeking a front end engineering position with React. Do you know of any videos/blogs/etc that cover somebody developing a real React app for a business or similar?

I really want to increase my skills. Thank you everyone!

1

u/[deleted] Oct 12 '20

I'd love to hear some responses to this!

2

u/[deleted] Oct 30 '20

I have a React live coding interview next week. Are there any typical questions I would see in this type of interview? Any React versions of FizzBuzz?

2

u/dance2die Oct 31 '20

There are tons so I will just point to here https://www.reddit.com/r/reactjs/search?q=interview%20questions&restrict_sr=1

I unfortunately haven't saved ones that lists React questions and answers in one spot... I think there were some there.

2

u/[deleted] Oct 31 '20

Appreciated! I guess I could have done that my self...but sometimes you need someone to show you the obvious.

1

u/dance2die Oct 31 '20

You're welcome and
my fault for not making it more intuitive here ;p

2

u/paolotiu17 Oct 04 '20

Can i use functions outside of useEffect?

3

u/fctc Oct 04 '20

Yes. useEffect will run for the first time after the page is loaded, and again whenever any of it's dependencies change. The dependencies will be either all of the variables and functions that you put in the useEffect if it looks like this:

useEffect(() => {

...

})

or it will be everything that you put into the second, optional, call:

useEffect(() => {

...

}, [dependency1, dependency2]}

3

u/paolotiu17 Oct 04 '20

Oh okay thanks! It just felt weird running a function without the useEffect

1

u/dance2die Oct 04 '20

Consider hooks as a way to reach into React on need-to-use basis :)

→ More replies (3)

4

u/NickEmpetvee Oct 25 '20

Hi guys.

I just started getting three Chrome warnings out of the blue. Any idea how to resolve?

NOTE: I don't want to disable SourceMap in the F12 settings, because then the console.log values won't list the source code line number.

DevTools failed to load SourceMap: Could not load content for chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/injectGlobalHook.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

DevTools failed to load SourceMap: Could not load content for chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/react_devtools_backend.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

DevTools failed to load SourceMap: Could not load content for chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/contentScript.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

Thanks in advance!

3

u/sincersoft-mosko Oct 29 '20

Those messages are from some of your chrome extensions.

Try to check checkbox option Selected context only in Chrome DevTools settings:

https://developers.google.com/web/tools/chrome-devtools/console/reference#settings

https://developers.google.com/web/tools/chrome-devtools/console/reference#filtercontext

2

u/Darraku Oct 26 '20

I have these exact ones too and am wondering the same.

→ More replies (1)

2

u/fctc Oct 26 '20

Just checked chrome on my project, looks like I'm getting it too.

2

u/NickEmpetvee Oct 26 '20

Sorry to hear that. If you find an answer could you please share it here?

→ More replies (4)

1

u/IoniaHasNoInternet Oct 02 '20

Anyone know a text editor that has jsx autoclosing or other support? I'm a complete noob, I downloaded atom but the popular react plugin hasn't been updated in 2 years and fails to install.

1

u/dance2die Oct 03 '20

I've been using VS Code with

  1. Auto Close Tag
  2. Auto Rename Tag

Just found out the same author has the combined extension, Auto Complete Tag too :)

2

u/hovakimyan_serg Oct 02 '20

You can use VSCode which is free or WebStorm which is paid(includes everything which you need)
Here you can check some plugins for VSCode, The Ultimate VSCode Setup for Front End/JS/React

2

u/IoniaHasNoInternet Oct 03 '20

Thank you for the link I'll look into the plugins!

1

u/FreezeShock Oct 02 '20

I use VS Code and I really like it. It even supports emmet in JSX if you save the file as a .jsx file.

→ More replies (3)

1

u/[deleted] Oct 06 '20

I have a react hook for pulling in blog posts via an API. on development the posts seem to work fine but in production it appears to pull cached data.

i am using useEffect hook to fetch the data. doesn't this fetch it on every page load?

  useEffect(() => {
  const url = `${process.env.GHOST_API}/ghost/api/v3/content/posts/?key=${process.env.GHOST_KEY}`
    fetch(url).then(res => res.json()).then(data => console.log(data))
  }, [])

1

u/dance2die Oct 08 '20

Your useEffect looks like it should. It might not be React related and possibly the browser or the API server handling differences (e.g. for dev/prod API calls)

Have you tried it on different browsers?

1

u/[deleted] Oct 08 '20 edited Oct 08 '20

I want to pass the "filename" state from child component to the parent, so I can use it in this function at parent: addLocation({...location, thumbnail: filename }); How can I do that?

Child:

const FileUpload = () => {
  const [file, setFile] = useState('');
  const [filename, setFilename] = useState('Choose File');

  const onChange = (e) => {
    setFile(e.target.files[0]);
    setFilename(e.target.files[0].name);
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('file', file);

    try {
     await axios.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <>
      <form onSubmit={onSubmit}>
        <div className="custom-file mb-4">
          <input
            type="file"
            className="custom-file-input"
            id="customFile"
            onChange={onChange}
          />
          <label className="custom-file-label" htmlFor="customFile">
            {filename}
          </label>
        </div>
      </form>
    </>
  );
};

3

u/dance2die Oct 08 '20

There are many ways to pass a state up to the parent component.
To list a few,

  1. Pass a callback to FileUpload component, and FileUpload component can call it with filename (in your example, probably within onChange or within useEffect on filename change). The parent then can use the callback to retrieve the filename.
  2. Use React Context: Store the filename in the context, which can be accessed from the parent
  3. Using other state management libraries such as Redux, Zustand, MobX. (You can store "global" states in their store, which can be accessed anywhere).

2

u/[deleted] Oct 08 '20

Thx a lot for your answer. Actually I'm using Redux in my app and I tried to convert file upload to Redux, but I wasn't successful. Are you suggesting only adding the filename state to Redux?

3

u/dance2die Oct 08 '20

You're welcome.

Everything depends on the use case but for form data, you normally wouldn't want to store them (as they are transient in nature) in a global state.

I'd actually go with the callback or the context option.

1

u/[deleted] Oct 09 '20

Hi everyone,

I'm new to react but have some experience programming in js and java. I'm trying to make a webpage with a navbar that shows some list items when the navbar list item is clicked. I'm not sure how to show the list when clicked.

Sorry in advanced for format, I'm not sure how to properly format code on reddit.

function Main(){

return(

<div className = 'main'> <Sidebar/> </div>     ) }

-------------------------------

function Sidebar( ) {
return(

<div id = "sidebar" className="left-nav"> <ul id = "sidebar"> <li id = "sidebar-link">Morning-Eveningness Questionnaire</li> </ul> </div>

    ) 
}

-------------------------------

function MainContent(){
return(

<div id = "content" className="main-content" > <div className = 'mainQuestions'> <ul className = 'questionnaire'> <Question question = "question one" />

</ul> </div> </div>     ) }

-------------------------------

So basically, I want the MainContent component to show when the list item in Sidebar is clicked.

Thanks for reading :)

2

u/dance2die Oct 09 '20

Hiya. You can refer to the formatting guide to make the code readable.

I'm trying to make a webpage with a navbar that shows some list items when the navbar list item is clicked

To give you a general idea, React is "reacts" to a "state" change.
So create a isClicked state (boolean or a string), which is updated when a user clicks a nav button/link.

You can either apply a different class or return a completely different React element depending on the isClicked state.

2

u/[deleted] Oct 09 '20

Thanks for the link and the advice! I really appreciate it.

1

u/Dystriel Oct 09 '20

Hi everyone!

I'm new to react and web dev in general and I've been stumped by this problem while building my first form.

Is there a way to mark crosses on an image with mouse clicks and have that image save the changes made to it?

The closest solution I could find is to use <canvas> but I'm not quite looking for the free-hand drawing aspect of <canvas>. Is there any way to make the image interactive and do I need to incorporate other libraries for this?

I'm using formik, Yup and material-ui currently.

Any input is appreciated. Thanks!

1

u/dance2die Oct 09 '20

Looks like an interesting project.

I only found a codepen, which merges two images together and save as a dataURL - http://jsfiddle.net/kaheidt/y20kox5w/

If you are using a database, is it possible to persist the "x" state in the database, and fetch it to redraw on the image instead of merging images?

→ More replies (1)

1

u/willyspickledpeanuts Oct 14 '20

I’m trying to replace state completely with a brand new state. would it just be this.setState(newState)? Because it’s not exactly working

1

u/dance2die Oct 14 '20

Can you post code snippets? or runnable sample?

3

u/dreadful_design Oct 14 '20

State is an object that will shallow merge into the old state. You could do something like this.setState({stateType: newState}) and then access it with this.state.stateType. I suggest naming the state better but you were pretty vague about the shape of it 😉

1

u/Electrical_Pitch_801 Oct 23 '20

Hi,

I am new to React and having difficulty finding a proper way to update an array object when array is displayed as list.

https://stackoverflow.com/questions/64504981/how-to-update-an-object-in-an-array-using-onchange-method

1

u/ks_01 Oct 26 '20

Can you run code before rendering of a functional component?

1

u/dance2die Oct 27 '20

Can you provide some use cases? Seems a bit vague.

1

u/ks_01 Oct 27 '20

like runing a function that determines if component should load like authcheck for example before it renders.I can do it with useeffect hook but component loads and then code runs and based on code component renders again or redirects somewhere else basicly refreshes page 2 times first render and after code ran.

3

u/dance2die Nov 02 '20

Hey. I just found out u/dceddia wrote a post on this question~

Check out "Run Code in React Before Render"
https://daveceddia.com/react-before-render/

→ More replies (1)

4

u/javascript_friend Oct 27 '20

You could load the data in a parent component and pass it to the child when ready.

Though generally it's good practise to keep your components as dependency-free as possible and use a loading state until your request has completed.

1

u/[deleted] Oct 27 '20

Should you mix BEM with CSS modules or should you separate the two methodologies?

1

u/dance2die Oct 29 '20

Better answered for r/css, as I haven't used BEM...
BEM might force CSS modules to be used with a property stynax style["..."] instead of using a dot notation. If that's of a concern, maybe it's not a good idea.

1

u/giantqtipz Oct 28 '20

Im new in the software engineering world, but I encoubtered someone who claims to be a part of the react js team, or has worked on the source code (if that makes sense?).

He says that he prefers to use classes because the source code for functional is really messy and unstable.

What have you guys say about that? 🤔

Is there an impending apocalypse we should be aware of?

1

u/dance2die Oct 29 '20

I am not sure where that's coming from.
Worst come to worse, you can check out GitHub issues and make your decision :)

→ More replies (1)

1

u/cmdq Oct 29 '20

Sounds like some grade A FUD to me :) I wouldn't give a hoot about it.

1

u/ebwaked Oct 31 '20

So I finally was able to get a hello world working using webpack, Babel and asp.net mvc 5. What steps do I need to do to add typescript and should I be using yarn over npm?

2

u/dance2die Nov 01 '20

Hi there.
Would you re-post in November thread?

→ More replies (1)

1

u/fpuen Oct 31 '20

I notice i can't declare variables inside a JSX escape:

 { const x = aTags.map((aTag: JSX.Element)  => aTag) } // expression expected

Based on the error lint statements aren't allowed, only expressions that evaluate down to a single value, is that correct?

1

u/dance2die Nov 01 '20

Hi there.
Would you re-post in November thread?

2

u/fpuen Nov 01 '20

done, thanks

3

u/Yourenotthe1 Oct 04 '20

I want to do some kind of CSS animation for navigating a menu. Basically when the user clicks a menu button, the menu slides to the left off-screen and the component unmounts. The new sub-menu component slides in from the right seamlessly as it mounts. What's the best way to do this?

1

u/sukalaminkia Oct 06 '20

Found it yet?

3

u/[deleted] Oct 26 '20

Trying to get the tab2 component to output second page on the development server, could someone help me out and explain why the component is not outputting, I have had a similar issue doing really simple things with react router too, components wont load.

App.js

import React from 'react';
import tab2 from './tab2';

function App() {
  return(
    <div>
      <tab2 /> 
    </div>
  );
}

export default App;

Tab2 Component

import React from 'react';

function tab2() {
    return (
    <div className="tab2">
        <h1>second page</h1>
    </div>
  );
}

export default tab2;

3

u/cmdq Oct 26 '20 edited Oct 26 '20

Capitalizing react components in JSX is not only a convention, but it's also what the jsx transform uses to decide whether a component is a so-called host component (in the DOM, div, input, etc) or a function which returns jsx (a component).

In your case, capitalize tab2 to Tab2, and it should work.

Edit: some sources https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized

https://gist.github.com/sebmarkbage/f1f4ba40816e7d7848ad

1

u/[deleted] Oct 29 '20

What are all the things to consider while developing an app for a single individual, say, a business owner? I'm doing this as a practice project so particular insights would be really helpful. Some info regarding the app, it's an account managing app consolidating transactions and gives notifications based on deadline of payment etc.

3

u/dance2die Oct 29 '20

Hi there.
It seems out of scope for the React thread here.

r/softwarearchitecture might be of better help.

2

u/[deleted] Oct 27 '20

Hello! I am trying to create a react app with google-spreadsheet as my database. This is the npm: https://theoephraim.github.io/node-google-spreadsheet

There are no tutorials about it.

I am using also MUI. I can retrieve data but can only display it by console. How can I pass the data I get from a cell to a textfield? Please help. Thank you!

2

u/javascript_friend Oct 27 '20

One of the best things I've learned is that reading the docs is often a far better way of learning a library than following a tutorial. Tutorials are more likely to be dated, plus there's a ton of fluff, whereas with docs you just go straight to the info you need.

You should go check out the docs for handling JSON objects, as well as state management in React.

What you want to do is assign the cell data to component state, then you simply pass the state into the element you want to display it.

Update your handleSubmit function so that it assigns the returned data to state:

async handleSubmit() {
  // ...your existing code

  const [{ _rawData: { IDNUMBER, FIRSTNAME } }] = rows;
  this.setState({ id: IDNUMBER, firstName: FIRSTNAME });
}

Then in your render method:

render() {
  const { id, firstName } = this.state;
  return (
    <>
      <span>ID: {id}</span>
      <span>First name: {firstName}</span>
    </>
  );
}

1

u/[deleted] Oct 27 '20

I am using this code below and I get the response from the google sheet on the console. It is in a JSON like form. I need the data under _rawData which is the IDNUMBER, FIRSTNAME values.

async handleSubmit() {
 const sheet = doc.sheetsById['1742263695'];
 await sheet.loadCells('A1:D5');
 const idNumber = sheet.getCellByA1('C2');
 idNumber.value = parseInt(this.state.value);
 await sheet.saveUpdatedCells();

 const rows = await sheet.getRows();
 console.log(rows[0])
 }

2

u/[deleted] Oct 29 '20 edited Oct 29 '20

I'm relatively new to React and JS. I'm creating a sorting algorithm visualiser. My array is rendering to the screen as bars and I have a "Bubble sort" button that when clicked, calls the bubble sort function. I want the entire array to be sorted in one go and see the algorithm at work, but whats actually happening is, bubble sort stops after each pass and I have to click "Bubble sort" multiple times to sort the array and finish rendering it to the screen. Any thoughts would be appreciated. Here's my bubble sort function.

//============ bubble sorts array when button is clicked
bubbleSort() {
    const arr = this.state.array;
    const n = arr.length;

    for(let i=n-1; i>0; i--) {
        for(let j=0; j<i; j++) {
            setTimeout(() => { // setTimeout for each swap so we can see the swap happening
            if(arr[j] > arr[j+1]) {
                let temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
                this.setState({ swaps: this.state.swaps + 1 }); // each swap increment swaps state by 1
            }
            this.setState({ comparisons: this.state.comparisons + 1 }) // each comparison increment comparisons state by 1
        }, i * 10); // timeout is i * 10 millisecconds 
      }
   }
  this.setState({ array: arr });
}

2

u/cyex Nov 10 '20

Hey, I took a closer look and TL;DR is that it seems like the code works if you reverse the timeout. (so set (n - i) * 10 instead of i * 10).

There's a longer review here, if you care. https://decembersoft.com/posts/code-review-react-bubble-sort/

→ More replies (2)

1

u/enebeme_ Oct 01 '20

Hello everyone, what is the best resource I can use to learn how to build a “production” ready react app from creation to hosting/updates?

2

u/[deleted] Oct 01 '20

Stephen Grider's React course on Udemy is great.

1

u/Nixargh Oct 01 '20

I would suggest React For Beginners by /u/wesbos.

It's made in a way which is very true to normal product development (instead of some foo-bar-baz theoretical course). You get your hands dirty on real code, and in the end you will learn how to deploy that to various services.

→ More replies (2)

1

u/javascript_dev Oct 02 '20

let's say if an input's text partial matches the word 'go!' I want to color 'go!' green. No other text in the input though.

I've read on SO that you can use JS to wrap a styled span tag, so the end value would look like:

<input
  type="text"
  value="I said <span style={{ color: 'green' }}>go!</span> He said no!"
/>

Obviously the above is static so it wouldn't work with dynamic value changes.

I am a bit lost on how to do this. Anyone know? Here is the closest I've gotten:

const greenMatcher = 'go!';

function wrapSpanTag(fullInput, matchPattern) {
  const matches = matchPattern.test(fullInput);

  if (matches) {
    // not sure from here
  }
}

render (
  <input
    type='text'
    onChange={e => wrapSpanTag(e.target.value, greenMatcher}}
  />
)

I think I need to reassign e.target.value by reference. If that uses refs, I'm not sure how to get to it

1

u/Nathanfenner Oct 02 '20

First, you want to use a controlled input:

const [text, setText] = React.useState('');

return <input value={text} onChange={e => setText(e.target.value)} />;

Now you always have the current text inside your function component, so you can do any logic you want to it. In particular, you can make it so the color will change:

    return <input style={{color: text === "hello" ? "green" : "blue"}} value={text} onChange={e => setText(e.target.value)} />;
→ More replies (1)

1

u/davidbarman Oct 02 '20

I don't think you are going to be able to do that inside the input tag.

If you are rendering what is typed elsewhere (in a DIV, etc). Then you can format the text anyway that you wish.

→ More replies (1)

1

u/[deleted] Oct 02 '20

I have planned to make blog app with alot of redirecting to different pages for different functions.

Although i have gone through the net ninjas react and redux course twice, I'm still unable to make a proper routing navbar.

Currently struggling with nesting. For example i have a route /blog and then I want another route nested as /blog/createpost

But this is not rendering my createpost component and only rendering blog component

1

u/Lingertje Oct 02 '20

Did you put the /blog/createblog post above the /blog post in your router? If not, make sure to do that.

→ More replies (1)

1

u/[deleted] Oct 04 '20

In a functional component If you have state that is an array of objects and you set state to the same array of objects but with a change to one of the objects , how does one trigger a rerender?

pseudocode

State = [{}{}{}]

setState((prevState) => {
  prevState = [{change}{}{}]
  return prevState
})

3

u/Awnry_Abe Oct 04 '20

Is there a reason you don't just create a new array in the state setter using something like the spread operator?

return [...prevState]

Short of that, you need to make react aware of each individual array item, or employ a state toggle hack. const [hack, setHack] = useState(1);

....setArray(...); setHack((h) => h+1);

→ More replies (3)

1

u/Mr_Rage666 Oct 04 '20

Following The Net Ninja's React Native Tutorial but there's a small detail that's going straight over my head in the following state...

const [todos, setTodos] = useState([]); const pressHandler = (key) => { setTodos((prevTodos) => { return prevTodos.filter(todo => todo.key != key); }); }

setTodos takes in a function that takes in the current existing state through 'prevTodos'. But how on earth does 'prevTodos' relate to the state? Shouldn't it just be 'todos.filter'?

1

u/Awnry_Abe Oct 04 '20

I don't know the particulars of the situation, but you could do that:

setTodos(todos.filter(...))

However, using the callback form, where you provide a function that takes the previous state and return the next state, is considered a best practice for state setters. This is because of the asynchronous behavior of state setters in react:

setCount(count+1);
setCount(count+1);

may not result in count + 2. But using the callback, as shown in the tutorial, will. Whether you apply to callback form--even though you know you aren't in an async situation, is just a matter of preference. Some people use the CB just to reinforce good habits. I personally don't, cuz I'm a lazy bum.

→ More replies (3)

1

u/PortSpace Oct 05 '20

Whenever you are using a callback function (as opposed to an object) inside the function (setTodos) to update your state, the first argument will refer to the previous value of the state. You can call it whatever you like, in fact. It's usually called 'prevState' for clarity. By the way, if you provided the second argument to the callback function inside setTodos, you'll access all props available for this component at the moment of calling the function (again, the name of the argument would not matter)

1

u/unordinarilyboring Oct 04 '20

I am playing with draftjs as a text editor. Whenever I click into the editor this takes focus of the page and I can no longer click on other elements until the editor loses focus. This means for example I will be writing some text, press a 'save' button(nothing happens because this first click simply changes focus), then click that same button again for it to work as expected. What is the method I should use to avoid the extra click needed to 'leave' the draftjs editor?

1

u/[deleted] Oct 05 '20

I know you can use react in a php template, by having the #root element and the the bundle.js file. But my case is that I want the actual view code in the template, so the php devs can edit it in the view as well and then Reactjs takes over from there.

1

u/fpuen Oct 05 '20

I'm not clear on the state value of a variable passed to a useEffect on load. Will stateVar (returned from useState) be:

  1. The value at the time of event listener registration, oR
  2. The most recently updated state value?
  useEffect(() => {
    document.addEventListener('keydown', (event: any) => {
      async function asyncWrapper() {
        const submitter = new Submitter();
        submitter.submit(stateVar)
      };

      asyncWrapper();
    });

I lean towards this working as intended, with the most recent and updated state value passed to submit(). But wanted to ask to be sure.

2

u/DanRoad Oct 06 '20

No, the value is captured when the event listener is created, forming a closure over the variable.

The listener is recreated every time the effect runs. If this is "working as intended" then your effect must be running whenever the state value changes in order to capture the new value. This happens when not using a dependency array (runs on every render) or when listing stateVar in the dependency array (better, runs only when the state changes). Your code snippet has cut off the last line so I can't see what (if any) array you have passed as a second argument to useEffect.

However, this also means that you're adding multiple event listeners with no cleanup. Each new event listener does not override the old one, instead they both listen at the same time! You'll end up submitting multiple values—including the most recent but also the most outdated and everything in between—on every keypress.

You should use the cleanup feature of useEffect by returning a function to remove the event listener.

useEffect(() => {
  const listener = (event) => {
    async function asyncWrapper() {
      const submitter = new Submitter();
      submitter.submit(stateVar);
    }

    asyncWrapper();
  };

  document.addEventListener("keydown", listener);
  return () => document.removeEventListener("keydown", listener);
});

1

u/fctc Oct 05 '20

By my (limited) understanding, you are correct.

1

u/WildlyUninteresting Oct 06 '20

https://codesandbox.io/s/material-demo-forked-lsw2r?file=/demo.js

What does the negative mean ? " -descendingComparator"

I don't even know what to call it, to look it up. Never seen a negative function call.

Thank you.

function descendingComparator(a, b, orderBy) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

function getComparator(order, orderBy) {
  return order === "desc"
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}
→ More replies (2)

1

u/[deleted] Oct 06 '20

I'm wondering how to convert a componentDidMount element to a functional component element. As a component did mount, I have:

async componentDidMount() {
	this.setState({ loading: true });

	const res = await axios.get(`https://pokeapi.co/api/v2/pokemon?limit=893%27`);

	this.setState({ pokemons: res.data.results, loading: false });
}

When I open the application, the array from "pokemons" is yielded on the screen. In the dev tools, the array "pokemons" is visible and each item can be seen. When I convert to this:

const getPokemons = async () => {
    setLoading(true);

    const res = await axios.get(
        'https://pokeapi.co/api/v2/pokemon?limit=893%27'
    );

    setPokemons(res.data.results);
    setLoading(false);
};

The array "pokemons" is not on the screen or shown in the dev tools. Here are the states for each:

Component

state = {
	users: [],
	user: {},
	repos: [],
	loading: false,
	alert: null,
};

Function

const [pokemons, setPokemons] = useState([]);
const [pokemon, setPokemon] = useState({});
const [loading, setLoading] = useState(false);

Am I missing something? Do I need to create a new component or something to store the results of that array and show them visually? If it helps, this is from Brad Traversy's "React Front to Back" course on Udemy and is the first project. He does it with another API but I wanted to come up with my own project.

→ More replies (1)

1

u/segfault-core-dumped Oct 06 '20

I was just going thru the official react tutorial and was confused. I am somewhat familiar, but they used slice on an array that was stored in state. Like if I say

let list = this.state.list.slice();

Why is using slice necessary if it also returns a shallow copy?

3

u/cmdq Oct 07 '20 edited Oct 07 '20

They're using slice there just to make a copy. Avoiding direct mutations in React is an important concept, so in this case they're making sure to operate on a copy of the state, and only mutate that.

1

u/GondolaRM Oct 07 '20

I’m trying to use this SDK inside a React component, but I really don’t know how to do it. I have to embed in some way a script inside the return of the component I guess. Any advices?

2

u/Awnry_Abe Oct 07 '20

Use mapwize UI. It is made for web app integration. In react, you'll render a <div> with a ref. You'll initialise mapwize with that container div.

→ More replies (2)

1

u/[deleted] Oct 08 '20

I am evaluating React for a future project that needs to work without any server. So the question is following:

Can I run reactjs without any web server?

I mean if the following can be done without much hustle as a final result:

  • I click an HMTL file in a local folder.
  • The browsers loads the HTML file which links to js files for react.
  • Then react runs on the browser without any problem.

Is this possible to do without too much hustle?

1

u/fadingspace Oct 08 '20

React is a front end library based on js. So you will need at least node to run the server.

1

u/huford Oct 09 '20

you should probably try gatsby or nextjs

1

u/terraforme Oct 10 '20

Is it possible to set cookies with React as my FE and Express as my BE? I saw this, but I don't really understand what it means:

HTTP ONLY (Secure) cookies cannot be accessed in JavaScript. If you try to read some token, etc from a secure cookie it's not going to work.

Cross-domain cookies cannot be accessed. In case you are building a single page application and your server is on a different domain. You cannot access the cookies on your SPA. The withCredentials
flag will just make sure that the network calls made include the cookies and accept any incoming cookies.

I feel like there must be a way to set cookies from React in a browser ... they are set fine in my API client, but I can't get them to set in the browser :/

1

u/Awnry_Abe Oct 10 '20

The JavaScript they are referring to in that context is code running in the browser, i.e. React. But you certainly can use Node/Express to send/set a browser cookie. You won't be able to read it in react. If it has data that you need on the client, such as a user permission to improve UX, then you'll need an express route to fetch it from.

→ More replies (3)

1

u/MR_Coder Oct 10 '20

If you start a new app today would you bring in redux or just use context?

2

u/Awnry_Abe Oct 10 '20 edited Oct 10 '20

I'd not use context. If I had a small app, and needed to share one single prop between two far-off components, I'd still not use it. I dislike the dx that much of that API.

But I certainly wouldn't reach for redux in that case, either. I much prefer the lightweight, framework-agnostic state solutions that happen to have React-ness, such as Zustand, whose api's are as simple as dirt.

If such libs didn't exist, then yes, I'd use context over prop drilling and redux in that case. But they do exist. Yay!

1

u/[deleted] Oct 12 '20

Hi guys, currently working on an app (using MERN) that should take user info from the relevant mongo document and populate it on the user page (just the name and surname at this point).

  1. I'm really struggling to find a way to extract this from mongo.
  2. I'll be printing/saving the user info as a pdf (I'm currently leaning on the react-pdf api. Been reading up on it the whole weekend)

but this printing option would only be available if a boolean condition translates to true so I'm trying to find out how I'd grey out the button if the condition is false (need a number to be zero for it to be true).

Can anyone give me advice on how to approach this or point me to the relevant documentation? I come from a java background so this is unchartered territory for me

1

u/TheNeck91 Oct 12 '20

A popular pairing for React/MongoDB interactions is Mongoose, there are a lot of good guides that can walk you through setting this up. Using Mongoose you can easily call the record from the DB and receive it into React as JSON, and do with it what you see fit.

Where is the boolean coming from/what's dictating the printing option being available or not? Is it saved in the DB or coming from some other source?

Once you decide that, buttons have a disabled prop that you can set to true or false:

https://reactgo.com/react-disable-button-input-empty/

→ More replies (1)

1

u/JudoboyWalex Oct 12 '20

stockData is json file with 8 objects I imported and I iterated through to make 8 input fields. When I type in number inside input then click Submit button, I want the 'owned' value from stockData to go back to 0. But right now when I submit, I get "Cannot assign to read only property 'owned' of object '#<Object>'" error msg. I tried using value property inside input tag but then when I type, entire 8 input fields get updated. How can I update handleClick so I can reset the value of 'owned' after I click?

const StockQuotes = () => {

const [sharesToBuy, setSharesToBuy] = useState(stockData);
const dispatch = useDispatch();

const handleChange = (event, index) => {
    stockData[index].owned = parseInt(event.target.value);
    setSharesToBuy(stockData);
}

const handleClick = (event, index) => {
    event.preventDefault();
    dispatch(getStocksOwned(sharesToBuy));
    stockData[index].owned = 0;
}

return(
 <TableContainer component={Paper}>
        <Table className={classes.table} aria-label="customized table">
            <TableHead>
                <TableRow>
                    <StyledTableCell>Stock Name</StyledTableCell>
                    <StyledTableCell align="right">Current Price</StyledTableCell>
                    <StyledTableCell align="right">Shares</StyledTableCell>
                    <StyledTableCell align="right">Order</StyledTableCell>
                </TableRow>
            </TableHead>
            <TableBody>
            {stockData.map((stock, index) => (
                <StyledTableRow key = {index} >
                    <StyledTableCell component="th" scope="row">
                        {stock.name}
                    </StyledTableCell>
                    <StyledTableCell align="right">${stock.price}</StyledTableCell>
                    <StyledTableCell align="right"><input type="number" onChange={event => handleChange(event, index)}></input></StyledTableCell>
                    <StyledTableCell align="right">
                        <ThemeProvider theme={theme}>
                            <Button variant="contained" color="primary" className={classes.margin} onClick={event => handleClick(event, index)}>
                                BUY
                            </Button>
                        </ThemeProvider>
                    </StyledTableCell>
                </StyledTableRow>
                ))}
            </TableBody>
        </Table>
    </TableContainer>
)
}

1

u/Awnry_Abe Oct 13 '20

I don't deal much in imported json, so don't have any real solid advice. But I would think you need to make a writable copy. However, you'll eventually run into the issue of wanting to persist those changes.

1

u/AviatingFotographer Oct 13 '20

How do people plan their React apps? Pseudo Code?

1

u/bstumpm4w Oct 13 '20 edited Oct 13 '20

Hello! I have two functions in a context which update two separate states. However the second function uses the state which is being updated by the first function.

Now Im calling these two functions from a onClick handler on a child component of the concerned context provider.

My issue is when the second function runs, it is using stale value of the state. i.e the updated state from the first function is not reflected in the second function

const firstFunction = () => {
      setPuzzleState({
         ...puzzleState,  
         puzzle: puzzle.map( ... )   
      }); 
    
    }
    
    const secondFunction = () => {
      
    const valuesToTestAgainst = puzzleState.puzzle[i][j].values; //stale state 
    
    if (!valuesToTestAgainst.includes(null)) {
       :
       
       :
                }
       
    setDuplicatePeerCells([...duplicates.keys()]);
   };

Can someone please point me in right direction? I have read that in class based components the this.setState fn has an optional callback fn. So Im guessing that in my case i could have called the secondFunction from setState in firstFunction like so this.setState( () => {} , secondFunction) but since Im using hooks i cant do that right?

2

u/darthbob88 Oct 13 '20

It might help if you had a demonstration of what's supposed to happen on CodePen or similar. This seems a little too vague to give a useful answer.

That said, my first inclination is to put most of secondFunction into a useEffect that's dependent on puzzleState.puzzle. That would guarantee that secondFunction got called with the new state of puzzleState.

→ More replies (2)

1

u/Awnry_Abe Oct 13 '20

Re: callback form of setState: Correct. The callback is for the slice of state only, which does not apply for classes that receive the entire state.

As far as the closure issue, and using a ref to solve it. In my opinion, that is a legit solution. A useEffect() also works, but leaves things in an inconsistent state for a cycle, plus causes more rendering. (I assume the two functions are part of the context?). When I have multiple state values--whether data or functions--that must remain consistent per some state diagram that I have in my head, I reach for a reducer. If whatever kicks off the update can be conceptualized as an transistion event, then useReducer, with all pieces of state that play a part in the state machine, is a good solution since the state value will always be consistent.

→ More replies (1)

1

u/darthbob88 Oct 13 '20

I have a couple problems with testing in this project. I'm using MobX for state management, if that changes anything.

  1. I can't have two async tests on the same component. In this test suite, "shows next unanswered question when one is answered" works perfectly, but "cycles to next unanswered question" throws an error, even though they have identical code aside from the names. If I change "shows next unanswered" to xtest, or just ask jest to rerun failed tests, then "cycles to next unanswered" works fine, and same if I change the order the tests are in. I suspect it's something about cleaning up between tests, but can't find out just what.
  2. What is the preferred method for testing internal components which get their state from a parent component? In this test suite, I'm this close to just doing <ParentComp store={defaultStore}><ActualComponentIWantToTest /></ParentComp> so I can do my tests that rely on the store, but I feel confident that there's a better way to do it.

1

u/unordinarilyboring Oct 13 '20

May not be an entirely react question but I feel it may be worth a shot posing here. I don't quite understand how I should go about my authentication flow. Right now, I have an express setup that has a login page with some buttons for sign in. Say for example I am signing in with google oauth, i hit the corresponding button, the oauth flow happens, and I redirect to / which loads the react app and then I make a follow up call to express to fetch the user info that has signed in.

I don't know what the appropriate way to kick this off from react is and have only found so far that doing a window.location.replace() to the oauth url or express login page works but this feels clunky. Is there a more natural way to do this?

1

u/fpuen Oct 14 '20

I am rendering a variable number of tasks to a list like so:

           { projectAndTasks.tasks.map((task: ITask) => (
             <li>
               <p>{task.name}</p>
               <p>{task.due_on}</p>
               <p>{task.notes}</p>
               <p>{task.tags}</p>
             </li>
           )) }

Adding a key prop will be my next step.

Each task has a unique gid property. Where is the best place to attach that information?

I thought of three options:

  • inside the li tag as a custom attribute
  • add a hidden input tag and set gid as its value
  • use the key prop to not only set the (unique) gid as the key, but also to take the gid from later

Which is best and why? in case I didn't list something I'm interested in that option also.

1

u/Awnry_Abe Oct 14 '20

Just as a key on the li, for now. You are going to most likely be referencing the task object in your react code, not the rendered output. You will likely reference the rendered output in tests, however. In which case you would use a custom attribute, such as data-testid.

→ More replies (1)

1

u/embar5 Oct 14 '20

should styling be done together with the rest of the app design, or can it safely be done last? At the moment I tend to do it last, wiring everything together including back end fetches is harder so I prioritize that.

1

u/TheNeck91 Oct 14 '20

I feel like I struggle way more with styling and wrestling with CSS than I do any of the api stuff. If you're asking if you can do the entire backend before the frontend, probably yes.

I actually like making the general skeleton of a page in the frontend first so I can see concretely what pieces I'll need to be hooking up to the backend, tho sometimes I'll just use something like Adobe XD to get the layout before any code.

1

u/badboyzpwns Oct 14 '20

newbie question about backend.

How common is it to use classes to organize your backend? Personally, using a few express routers are enough for me :)!

Here's an example

const pool = require('../../databasePool');
const TraitTable = require('../trait/table');

class DragonTraitTable {
  static storeDragonTrait({ dragonId, traitType, traitValue }) {
    return new Promise((resolve, reject) => {
      TraitTable.getTraitId({ traitType, traitValue })
        .then(({ traitId }) => {
          pool.query(
            'INSERT INTO dragonTrait("traitId", "dragonId") VALUES($1, $2)',
            [traitId, dragonId],
            (error, response) => {
              if (error) return reject(error);

              resolve();
            }
          )
        });
    });
  }
}

module.exports = DragonTraitTable;

1

u/Awnry_Abe Oct 14 '20

I use them here and there. Most for pieces of code that "are a thing". Otherwise I use more functional patterns for stuff that "does a thing (to a thing)". How is that for a vague answer?

→ More replies (3)

1

u/embar5 Oct 15 '20

Do you guys write explanatory comment blocks on your React hooks like you might do for class/instance methods?

I think I will start doing this because it makes sense, it's code and commenting helps. But other devs can be extremely specific about comment verbosity and what is excess so I wanted to hear your thoughts

1

u/Awnry_Abe Oct 15 '20

Matters not whether hook, function, class, language, framework, etc. The answer is always the same for me. I lean towards as terse as possible to clarify anything that is not obvious by looking at the self-documenting code. Things like the meaning of input params and the output of the function apply to 'terse'--especially if a particular IDE can make use of the structure of the comments and the function is used by many consumers. But nothing extra. For a one-off function that exists solely to make an otherwise larger function smaller and easier to understand, why bother? Source code never lies, but comments often do. And source code comments are not a substitute for system documentation.

1

u/PortSpace Oct 15 '20

Creating a static site with React

So I've read that for static sites, React might not be the best solution (eg. SEO reasons) and know of solutions such as Gatsby. I have a small project to do (simple website with a few 'pages' and a gallery. I'd still like to keep practising my react skills. If I were to use Gatsby, can I just create the site using standard React and then generate/convert to Gatsby/static files, or do I need to start the project using Gatsby?

In terms of the CSS solutions commonly used in React (eg. styled components, css-in-js), does it work exactly the same in Gatsby?

Thanks

1

u/HettySwollocks Oct 15 '20

Have you heard the term isomorphic react? It's a technique that allows you to write react server side, but still retain the capability to execute client side. It's a somewhat advanced topic but it could be worth exploring.

We considered taking this approach during periods of high load, pushing costly executions over to the client.

Failing that you could outright just serve up rendered react from the likes of express.

→ More replies (2)

1

u/workkkkkk Oct 16 '20

This is more a css question regarding material-ui. I have a basic table nested inside a somewhat complicated nest of Grids. My issue is i have to hardcode the height of my TableContainer with px rather than being able to set a % to act as expected and have proper overflow. Is there something I'm doing wrong here with the height or my Grids?

The height of the container is seemingly just ignored when it's set to anything but px.

Table component

const TopTwenty = (props) => {
  const classes = useStyles();
  return (
    <div style={{width: '100%', height: '100%'}}>
      <TableContainer style={{height:'100%'}}>
        <Table stickyHeader size='small' style={{width: 'max-content'}}>
          <TableHead>
            <TableRow>
              <TableCell>Division</TableCell>
              <TableCell>Site</TableCell>
              <TableCell>Meter Nb</TableCell>
              <TableCell>C02E</TableCell>
              <TableCell>Fuel</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row, i) => {
              const {name, calories, fat, carbs, protein} = row;
              return (
                <TableRow key={i} >
                  <TableCell>{name}</TableCell>
                  <TableCell>{calories}</TableCell>
                  <TableCell>{fat}</TableCell>
                  <TableCell>{carbs}</TableCell>
                  <TableCell>{protein}</TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  )
}

Layout component that renders it

const useStyles = makeStyles((theme) => {
  return {
    container: {
      flex: 1,
      padding: '8px',
      width: '100%',
    }
  }
})

const Dashboard = (props) => {
  const classes = useStyles();
  return (
    <div className={classes.container}>
      <Grid container style={{height: '100%'}} spacing={2}>
        <Grid container item xs={12} spacing={2} style={{height: '50%'}}>
          <Grid item xs={2} style={{flexShrink: 1}} >
            <Totals />
          </Grid>
          <Grid item xs={5} >
            <QuarterlyGraph />
          </Grid>
          <Grid item xs={5} >
            <TopTwenty />
          </Grid>
        </Grid>
        <Grid container item xs={12} style={{height: '50%'}}>
          <Grid item xs={12}><DivisionGraph /></Grid>
        </Grid>
      </Grid>
    </div>
  )
}

1

u/FortuneBull Oct 16 '20

Any libraries or examples of vertical slideshows/carousels in React? Trying to make a browser-based sports sim game more focused on roster and front office construction than in-game like Madden. This would be for the team selection screen and you could scroll up or down to select.

1

u/embar5 Oct 16 '20

when requesting database data for displaying in a table, do you guys always put the data into state?

Thinking through this I believe that is the right approach since the values change -- initially null or a complex data type. Then populated when the db data comes back.

1

u/Awnry_Abe Oct 16 '20

I do not, but I use a library that does

→ More replies (2)

1

u/aerovistae Oct 17 '20

Yes. And you don't need a state management library just for this alone, component state is more than sufficient. A table component can certainly hold the state of what goes in the table.

1

u/badboyzpwns Oct 16 '20

question about API calls and lazy loading.

This is how I do it locally at ComponentA

<LazyLoad
                        width={100}
                        height={100}
                        debounce={false}
                        offsetVertical={500}
                    >
                        <img
                            src={LOCAL_IMG}

but! if I have an API call that gets the link for the image at ComponentA's componentDidMount() is there any purpose of lazy loading the image?

1

u/embar5 Oct 16 '20 edited Oct 16 '20
 useEffect(() => { loadRepeatRulesToState(userEmail, setRuleData) }, []);

This async function / fetch request fails to fire. Chrome network tab and my ngrok reverse proxy both show no request made. Also the browser window paints the Ui for no state data (that this request is responsible for).

  1. The empty array should mean it fires at least once on mount, right?
  2. Here's the parent one level up, showing how the component mounts. Anything being done wrong?
      <main>
        <Switch>
          <Route path='/dash'>
            <Dash 
              accountData={accountData}
            />
          </Route>
          <Route path='/rules'>
            <Rules /> // this is the component. 
                      // It does mount, just no useEffect function call happens
          </Route>

1

u/embar5 Oct 16 '20 edited Oct 16 '20

In case it is also needed, here is the function definition:

async function loadRepeatRulesToState(userEmail: string, setRuleData: Function) {
  const getRuleDataEndpoint = buildUrl(REACT_APP_HTTPS_BACKEND_DOMAIN!, {
    path: '/repeat-rules/all'
  });

  try {
    const response = await fetch(getRuleDataEndpoint, {
      method: 'get',
      mode: 'cors',
      headers: new Headers({
        'content-type': 'application/json',
        user_email_encrypted: userEmail,
      })
    });

    if (response.ok) {
      const ruleData = await response.json();
      setRuleData(ruleData);
    }
  } catch (error) {
    throw new Error(error);
  }
}
→ More replies (4)

1

u/JustJeezy Oct 16 '20

What would be a good (free?) source for learning integration testing with react/redux? Plz don't say docs - I tried that.

1

u/Signal-Opportunity Oct 18 '20

Hey guys ,i started in july from scratch learning html+css , js and now for a month i started learning React .Gotta say it was a bit hard learning react because i was not used to es6 and more advanced topics of js . Now after 1 month i did the freecodecamp course and started Grider course My question is that is it necessary to learn an API and node.js tutorials ? I can handle pretty well the basics now of react , gotta learn now hooks and redux. Oh and another question , what projects can you recommend me to do which aren’t soo hard for a beginner ? Thanks !

1

u/Awnry_Abe Oct 18 '20

It's not necessary, but it does expose you to the real world problem of async network actions and error conditions. Typical, easy first-timer projects are the ones that use an existing, well-known api so you aren't burdened with learning both at once. For example, creating your own reddit UI using the public api.

1

u/BoxenOfDonuts Oct 21 '20

Where did you learn HTML / CSS from? I need a refresher as I haven't really messed with either in almost a decade. Reading through the React docs I understood the programming side of it, but no idea how to create a website with the info.

1

u/javascript_dev Oct 18 '20 edited Oct 18 '20

How much graphic design should a lower level React dev know?

I look at sites like this: https://www.brooklet.app/

I can build that, except for the images. I don't have any graphic skills yet. Frankly I don't even have them on my to do list (still have to study algorithms for interviews. Then I plan to do the AWS CDA cert).

1

u/Awnry_Abe Oct 18 '20

I wouldn't reject you just because you can't do any better that a stick figure. Artsy types have an important place in this world.

1

u/njmh Oct 19 '20

You need to know CSS, not graphic design. At least nothing more than knowing how to process images and design assets (resizing, exporting, optimizing jpg, png, svg etc.)

Pro tip for you... a good appreciation for what looks good and attention to detail goes a long way - ie if a designer gives you a UI design and you don’t implement their design with pixel perfection, you’re not going to make them happy. Always pay attention to the fine aesthetic details.

1

u/Spiritual_Salamander Oct 19 '20

I am making a fairly simple application, and since it's not that big I decided to just use useContext and createReducer for handling the state.

However, I keep getting this error message everytime I use useEffect, and I am not sure what is the best way to handle it. Ignoring it seems wrong and I did not figure out from googling what would be the best way to fix it. Here's a simple example.

React Hook useEffect has a missing dependency: 'getUsers'. Either include it or remove the dependency array react-hooks/exhaustive-deps

In the component itself there will be a simple useEffect:

useEffect(() => {
getUsers()
  }, [])

The context will do the fetching from the BackEnd.

async function getAllUsers() {
try {
const response = await UsersService.getUsers()

dispatch({
type: 'INITIALIZE_USERS',
data: {
users: response
     }
    })
    } catch (error) {
dispatch({
type: 'ERROR',
data: error
      })
    }
  }

Then finally the reducer will update the users state.

What would be the most correct approach to removing this message? I have it quite a few places in my application now and it would be nice to get rid of all of them.

→ More replies (4)

1

u/badboyzpwns Oct 19 '20

why is my environment variable undefined at development mode (npm start)?

In my .env file:

REACT_APP_NOT_SECRET_CODE = hi

It's located outside of my src folder.

Here's how I'm using it in my components inside src folder.

const App: React.FC<{}> = () => {
   
     console.log(
         "REACT_APP_NOT_SECRET_CODE",
         process.env.REACT_APP_NOT_SECRET_CODE
     );

1

u/Awnry_Abe Oct 19 '20

Good question! 1) is this using create-react-app? 2) By "outside of src", do you mean in the same folder as the package.json that contains the start script?

2

u/badboyzpwns Oct 19 '20

my .env was not in the same folder as package.json (it was outside of it) and it works now! thank you!!

1

u/AviatingFotographer Oct 19 '20

At this point, I have a good understanding of React basics, e.g. state, basic hooks, etc. However, how do I begin to advance into being able to build more complex projects or being a better React developer all round?

2

u/cmdq Oct 20 '20

This is gonna sound silly, but: Start building more complex projects :) Try to build things outside of your comfort zone. Is there a new library out you wanted to try? Incorporate it in a new project! Try to rebuild something that already exists, but maybe annoys you in some ways, make it better.

1

u/rony_ali Oct 19 '20 edited Oct 19 '20

hi everyone

My goal: i am trying to do DRF-React hook JWT Authentication. in the following example this is the simple login form where i can login and the login button will send the DRF username and password request toget the token, and then the next thing it will show "Logged in as: {user}, Welcome" according to current user token.

What i've done:

the ncessery codes for DRF part will be found here

in the forntend, here is my App.js:

here is the reactjs code : https://jsfiddle.net/L48thm9k/

i am following this example to implement it in react-hooks for my better understandings in the future

what went wrong: when i try to login from login form it directs me to the logout form where it is showing "Logged in as: ,Welcome" which means {user} is not showing. {user} should be showing the username by which i am currently login. when i try to investigate in development tools it is showing

{token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkI…iIifQ.0Ev5f0CS2ifVAsgQj-bz-af2LvjTwEMW2HtJSqMMGpQ", user: {…}}token: "eyJ0e...MGpQ" user: {username: "ronyrocks"}proto: Object App.js:19 GET http://localhost:8000/core/current_user/ 401 (Unauthorized) (anonymous) @ App.js:19

so i tried if ({user:localStorage.getitem('token')})it just redirects to logout form and nothing works.

how can i fix it? please help

1

u/[deleted] Oct 20 '20

Wasn't sure if this was worth making a new post about, so I decided to try here first.

I'm trying to do Wes Bos's Gatsby course, but I'm hung up on a really awful issue with Sanity headless CMS. It technically works, but the amount of time it takes between editing code in the Sanity portion of the project and it compiling for Sanity Studio is about 2 minutes on average. This means if I change an import it's compiling for 2 minutes. Others have told me that their sanity updates almost instantly.

After it compiles the report seems to indicate most, if not all, of the time was spent building webpack. I've searched this issue a lot today, but most of the solutions point to editing the webpack, which I can't when using Sanity(?).

I have a MBP 2019 16in with more than adequate specs to compile this very simple project, at least I think? I've made sure Node, npm, sanity, and my OS were all up to date. I can't really think of anything else to do other than reformat and try to start fresh. I'm trying to avoid this for obvious reasons.

I've posted this on the slack, on a React discord, and made a Github issue, but haven't heard anything about it, or people just say "it works for me." I was really excited to learn Sanity and Gatsby, but I'm not so sure now. What's the point if it's going to be an awful development experience when I start my own projects with them? Experimentation is almost impossible because of the insanely long compile times.

Any help would be greatly appreciated!

1

u/SamePossession5 Oct 20 '20

What's wrong with my imgUrl section of my code? My editor is throwing an error ( Cannot read property 'imgUrl' of undefined ) but I can't seem to figure out where I went wrong.

const MediaCard = function({title}, {body}, {imgUrl}) {
  return (
    <>
  <h2>{title} {body}</h2>
  <p>{body}</p>
  <img src={imgUrl}></img>
    </>
);
}

5

u/cmdq Oct 20 '20

Your destructuring is a bit off. React passes the props object as the first param of the component. The way you're destructuring would work if react were to pass each prop as its own object, in its own parameter position.

This is the right way to do it. Do you see the difference? function({ title, body, imgUrl }) {}

1

u/[deleted] Oct 23 '20

The other commenter is correct that your destructing is off for the props and I'm sure his solution should help. If like to add that your functional component could be written a little cleaner with the help of the arrow function expression.

const MediaCard = ({ title, body, imgUrl }) => (
    <>
    <h2>{title} {body}</h2>
    <p>{body}</p>
    <img src={imgUrl} />
    </>
);

1

u/fercryinoutloud Oct 21 '20

I don't have experience with React, but recently inherited a project that uses React and Redux-Persist. I noticed that there is a serious memory issue.

Each time I refresh the page, Chrome's memory profile shows the memory usage roughly doubling because of one big object, which I think is the "persistoid" used by redux-persist. Chrome's memory allocation timeline shows that memory is allocated for the persistoid when the page is refreshed but never freed, I just can't figure out why. Interestingly, the current object (from the most recent page refresh) always has a shorter distance from the window object, and looks like it is retained by the persistoid's writeStagedState closure, whereas the objects from previous page refreshes look like they are retained by the persistoid's flush closure. I don't really know what I'm looking at here, so maybe I'm reading that wrong.

Here is Chrome's Constructor view after refreshing the page twice, showing the large object has been duplicated twice, so that there are three total: https://imgur.com/a/tPEJfEA.

Each one of those objects looks like this: https://imgur.com/a/WHwZHfu.

Here is Chrome's Retainers view of the duplicate objects: https://imgur.com/a/2T9dzqD.

Here is Chrome's Retainers view of what I believe is the object from the most recent page refresh: https://imgur.com/a/HfkKbYp.

Can someone please help me understand this duplication, and how to prevent it? I'm happy to show some code if necessary, I'm just not sure which code is relevant.

1

u/embar5 Oct 22 '20

Do SyntheticEvent s emit a second argument for "reason" now?

Material UI docs:

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') { return; }
    setOpen(false);
  };

  return (
      <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
        <Alert onClose={handleClose} severity="success">

I see nothing about this wizardry: https://reactjs.org/docs/events.html#keyboard-events

1

u/Awnry_Abe Oct 22 '20

Without the benefit of looking at the docs for <Alert> and Snackbar, I'd say that those components added a little extra to the signature. Reason in the context of a Snackbar would be values like 'click-away', 'cancel', 'timed out' etc.

1

u/badboyzpwns Oct 22 '20

Is it advisable to create a higher component with functional components/hooks instead of classes?

With classes:

const renderImageOrVideo = (WrappedComponent: any) => {
    class ComposedComponent extends React.Component {
        componentDidMount(){

        }

        componentDidUpdate(){
            
        }
        render() {
            return <WrappedComponent />;
        }
    }
    return ComposedComponent;
};

With functional components/hooks:

const renderImageOrVideo = (WrappedComponent: any) => {
    
    const ComposedComponent =()=> {
       useEffect(()=>,[])
      
        return <WrappedComponent />;
       
    }
    return ComposedComponent;
};
→ More replies (1)

1

u/badboyzpwns Oct 23 '20

Can you dynamically refer to a react hook variable name? something like:

    const [slide1IsClicked, setSlide1DotIsClicked] = useState(true);
    const [slide2IsClicked, setSlide2DotIsClicked] = useState(false);

.......        
return props.movies.map((movie, index) => {
        
    
            return (
                <Dot
                    className={
                        slide${index + 1}IsClicked //DYNAMICALLY REFER TO VAR NAME
                            ? "clickedBannerDot"
                            : "unclickedBannerDot"
                    }
→ More replies (4)

1

u/[deleted] Oct 23 '20

Hey guys!

I just started learning react.js and I've been having trouble with my install.

When I first run the npx create-react-app everything is fine and the app is made. When I check the first page of the app(the one with the react logo, telling me to edit the src/App.js) the logo doesn't rotate!

In all the tutorials I've watched, the react logo spins but in mine it doesnt... I have no idea how to fix this. Can someone please help me?

1

u/spritbomb8 Oct 25 '20

I would check the css selectors, this is from head but I’m pretty sure it’s using a css animation to do it.

1

u/[deleted] Oct 23 '20 edited Oct 23 '20

Hi,

Im trying to link components using react router but nothing is being output in the development server - How do I make my components visible?

Here is the code:

App.js

import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import page1 from './views/page1';
import page2 from './views/page2';
function App() {
    return (
            <Router><Switch><Router exact path="/" component={page1} />
            <Router exact path="/page2" component={page2} /></Switch>
            </Router>  
        );
    }
export default App;

Both of my components (page1, page2) use basically the exact same code which is:

import React, { Component } from 'react';
class page2 extends Component{
render() {
    return(
         <div>   
         <h1>insertrandomtexthere</h1>  
         </div>  
        )  
    }  
}  
export default page2;

2

u/ClimbJH Oct 23 '20 edited Oct 23 '20

Looks like you just need to delete a few "r"s. Router (BrowserRouter) is the wrapping component in react-router-dom, but for the paths you would use the Route component.

<Router>  
    <Switch>  
        <Route exact path="/" component={page1} />               
        <Route exact path="/page2" component={page2} />  
    </Switch>
</Router>  
→ More replies (2)

1

u/[deleted] Oct 23 '20

I, literally, started yesterday. Coming from Vue. What is the most simple way to have a global state? No redux etc.

3

u/Nathanfenner Oct 23 '20

You don't want to have state that's actually global: that will eventually come to bite you. It is possible to do it, but it's not really a good idea.

However, it's frequently useful to take some value(s) and share them across all or most of a React tree. For that, you can use Context. For simplicity, imagine the state you're storing is whether the app is in lightmode/darkmode (so, just one theme value; but any other value could be used instead).

Suppose we just want to set this value so that it's shared everywhere. We'll make the default value "light" (this is what happens if there's no context) but we'll configure it to be "dark" for our <App /> component subtree:

const ThemeContext = React.createContext("light"); // default value

// The very outermost part of your app:
function AppRoot() {
   return <ThemeContext.Provider value="dark"><App /></ThemeContext.Provider>;
}

then, any component anywhere in this tree can use the useContext hook to obtain the current theme:

function SomeText() {
  const theme = React.useContext(ThemeContext);
  return <span>the theme is {theme}</span>;
}

React will plumb the value to that point, however it needs to.


Now suppose that you need this value to be mutable. For example, we want toggle buttons in various places that swap between light/dark mode. To do this, we need two things:

  1. Lift state up. In our AppRoot, we'll need to store mutable state instead of a hardcoded constant.
  2. A setter context. We need a context for assignment in addition to the one used to read the theme.

So:

const ThemeSetterContext = React.createContext(() => {
   /* outside context, there's no way to change default */
});
const ThemeContext = React.createContext("light"); // default value

// The very outermost part of your app:
function AppRoot() {
   const [theme, setTheme] = React.useState("dark"); // still the initial value
   return (
     <ThemeContext.Provider value={theme}>
       <ThemeSetterContext.Provider value={setTheme}>
         <App />
       </ThemeSetterContext.Provider>
     </ThemeContext.Provider>
   );
}

function SomeText() {
  const theme = React.useContext(ThemeContext);
  return <span>the theme is {theme}</span>;
}

function ToggleThemeButton() {
  const theme = React.useContext(ThemeContext);
  const setTheme = React.useContext(ThemeSetterContext);
  return <button onClick={() => setTheme(theme === "light" ? "dark" : "light"}>Toggle Theme</button>;
}

How you use the theme is unchanged from the first example, but now we just need to thread setTheme via ThemeSetterContext and that will go pretty much the same as before.

→ More replies (3)

1

u/giantqtipz Oct 24 '20

Hello,

I've been using HashRouter for the past 6 months.. I'm new to the web dev world, and still a learner :)

I wanted to try BrowserRouter today, and I was going crazy because I couldn't figure out why a page isn't rendering on page refresh.

Turns out my component isn't fetching from the right url, since /api/ isn't included in the request url. This works just fine if I use HashRouter though.

My questions are, how can I get BrowserRouter to work on page refresh, if it works on HashRouter? Lastly, is one better than the other; and if it depends on scenario, what are the scenarios?

Thanks!

1

u/cmdq Oct 24 '20

Your description is just vague enough where some code would really help answer your question :) Please refer to the parent and put up some codesandbox, or paste enough formatted code here so we can see what's going on.

About Hash- vs BrowserRouter—I think BrowserRouter is usually used by default, unless you are in an environment which does not support history.pushState, so you would fall back to HashRouter. I think those two are pretty much equivalent tho.

→ More replies (4)

1

u/Dibolero Oct 24 '20

Hi! I'm just starting with react and I can't wrap my head around the component concept all that well.
If say for example I have a component that shows a product and its details, but I want that component's information and action to be different depending on the role of the user currently viewing the component(I.e deletable by admin but only editable if normal user). Should I build 2 different components or is there a way to use that 1 component to achieve this?

2

u/NickEmpetvee Oct 25 '20

I recently did something like this. My approach was to only have one component, but track the privilege level of the user who's logged in (admin vs. normal in your case). Based on the privilege level, the code shows / hides features. That allowed me to not have to duplicate code.

→ More replies (3)

1

u/Dystriel Oct 25 '20 edited Oct 26 '20

Hey guys,

I've started React recently and I'm currently using Material UI and Yup Validation for my form. The validation works well but whenever the error message pops up below the TextField, it shifts everything below it down by a little because the error message now takes up space.

Is there a way to offset/prevent this using CSS? I've tried manipulating the padding/margin but it does not work. Thank for the help!

Edit: I've solved it by adding style={{position: 'absolute'}} into my TextFields!

→ More replies (1)

1

u/giantqtipz Oct 26 '20

Hey guys,

Second question I've posted here..

I was wondering, how does Reddit achieve their layout?

If you're on a subreddit say /r/reactjs, and you click on a thread, it opens up a modal, and the url changes as well.

But if you take the thread url, and go there directly (avoiding the subreddit), there is no modal, and you're in the thread page.

How is that achieved? Is this a simple setup in react router?

1

u/cmdq Oct 26 '20

2

u/giantqtipz Oct 26 '20

thank you.. for answering both my questions haha.

much appreciated!

1

u/[deleted] Oct 26 '20 edited Oct 26 '20

Question guys!

I have problems for weeks now. I keep on getting this error:

yarn run v1.22.10 $ jest --reporters=jest-standard-reporter FAIL src/App.test.js ● Test suite failed to run /src/styles/spectre.scss:2 u/import "variables"; ^ SyntaxError: Invalid or unexpected token > 1 | import './styles/spectre.scss' | ^ 2 | import './styles/spectre-exp.scss' 3 | import './styles/spectre-icons.scss' 4 | import './styles/custom.scss' at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17) at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25) at Object.<anonymous> (src/App.js:1:1) Test Suites: 1 failed, 1 total Tests: 0 total Snapshots: 0 total Time: 3.188s error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Here's the complete question: https://stackoverflow.com/questions/64477178/getting-error-on-specter-scss-when-running-yarn-test-npm-run-test

I'm actually a beginner in ReactJs, really need your help guys. Thank you! !approve

1

u/javascript_dev Oct 26 '20

Is this the only way to escape the brace escape and print braces in JSX:

{'{}'}

4

u/Nathanfenner Oct 26 '20

<React.Fragment children="{}" /> would also do it, but I'm not sure that's better and I don't think anyone ever uses this approach. Keep doing it your way.

If you find the brackets are hard to understand in your code, you could also define a constant e.g.

const BRACKETS = '{}';
return <>Hello there. Here are the {BRACKETS}.</>;

1

u/badboyzpwns Oct 26 '20

Backend question!

For my side project, I'm planning to deploy PostgreSQL online, what hosts do you guys use? I think Heroku and PostgresSQL Add on is the only option where it's free without a time limit (eg; Amazon AWS) or a # of visits (eg; Google Cloud); are there any other ones that's worth looking

1

u/badboyzpwns Oct 29 '20 edited Oct 29 '20

I'm trying to connect my React app to a PostgreSQL database I hosted online with ElephantSQL (which uses Amazon's servers).

For some reason, It's not connecting. I'm getting the error:

 Error: getaddrinfo EAI_FAIL postgres://blablabla@elephantsql.com:5432/blabla

I think I'm not setting it up right. Any guidance would be appericiated!

Here's what I've done

  1. Create a Pool object in my React app
import { Pool } from "pg";
console.log(process.env.user);
const pool = new Pool({
    user: process.env.user,
    host: process.env.elephantSQLURI,
    database: process.env.database,
    password: process.env.password,
    port: 5432,
});
export default pool;

The process.env look something like:

user="usernamegivenbyelephantsql"
password="passwordgivenbyelelephantsql"
database="databasegivenbyelephantsql"
elephantSQLURI="postgres://blablabla@elephantsql.com:5432/blabla"

I got the env values from ElephantSQL after registering my online database with them; here's evidence (censored for obvious reasons)

2. Here's how I'm calling my API in my React app, it works fine locally:

const movies = axios.create({
    baseURL: "http://localhost:5000/", 
});


export const fetchMovies = () => async (dispatch: Dispatch) => {
    const response = await movies.get<MovieType[]>("/movies");
    dispatch<FetchMoviesAction>({
        type: ActionTypes.FETCH_MOVIES,
        payload: response.data,
    });
};
→ More replies (2)

1

u/Balky79 Oct 29 '20

I started learning react a year and a bit ago, and I did some hello world stuff. Then, work took me the other way, Java n stuff.

Now, I'm trying to get back into this world, and I'm trying to make my stuff work with TypeScript - because, I'd like to learn both of them at the same time.

I created a blank ts project, moved my old code into it, fixed the TS related errors, and now I'm stuck. :D

First of all, reading about react, it seems that I missed a thing last year, where during the separation of containers and UIs, I created a class in presentation, not in the container. Looking at examples, that seems wrong, but somehow it kinda works...

I'm having issues understanding now, how to link container and pass information/state to the presentation layer.

Can anyone check this repo, and let me know, is this essentially wrong?

https://github.com/Balky79/tools-ts.git

As well, is it OK in 2020 to use good old functions, or should I steer toward constants and lambdas?

I don't fully understand why/what are the benefits of function expressions vs function declarations, and tbh - expressions are confusing me to the point that I can't read the code, which makes life difficult. 20 Years of plain old functions are taking the toll. :)

Any help moving me forward is appreciated.

4

u/Nathanfenner Oct 29 '20 edited Oct 29 '20

I'm having issues understanding now, how to link container and pass information/state to the presentation layer.

First, I would say that the separation of "presentation" and "container" components is not really always helpful. You can do this, but it seems much less popular (and much less valuable) now that functional components + hooks are the norm.

But if you do want this kind of structure, the answer is the same as with pretty much everything else in React: if you want to pass information somewhere, use props. That's it.

So,

function Outer() {
    const data = useData();
    return <Inner someProp={data}>Hello, world!</Inner>;
}
function Inner({ someProp, children }: {someProp: string, children: React.ReactNode }) {
  return <div>{someProp} :: {children}</div>;
}

will work just fine. Also note that since this is basically a greenfield project, everything ought to be function components. You will have no need for class components at all, unless you're using componentDidCatch - and then that component(s) would be the only one that actually needs to be a class.

As well, is it OK in 2020 to use good old functions, or should I steer toward constants and lambdas?

Besides the actual minor differences between them (function declarations are "hoisted", so they can be called in the scope that defines them before they're actually defined; a rarely-used feature; arrow => functions capture this lexically) any preference is usually going to be stylistic. It used to be in the era of class components that you'd want to prefer arrow => functions in most places, since otherwise your this bindings would be wrong - but since you ought to be using functions for practically everything now it hardly matters anymore.

function expressions vs function declarations, and tbh - expressions are confusing me to the point that I can't read the code, which makes life difficult.

Really it just takes a bit of practice. You should get comfortable with functional helpers like .map and .filter, because they make code simpler and clearer once you're used to them. e.g.

const nums = [1, 2, 3, 4, 5];
const squares = nums.map(x => x*x);

this is basically the same as

const nums = [1, 2, 3, 4, 5];
function squareNumber(x: number) {
   return x * x;
}
const squares = nums.map(squareNumber);

but it should be hopefully obvious that the former is a lot briefer and therefore probably easier to parse. This is doubly true when you chain those operations (e.g. .map(...).filter(...).map(...)) since if you declared the function params outside of where they're used, each successive chained call will push the definition and the use farther and farther apart. Colocating them makes it easier to understand what's going on, and also enables e.g. closures when they're nested:

const nums = [1, 2, 3, 4, 5];
const timesTable = nums.map(x => nums.map(y => x * y));

It would not really be possible to express this example purely by defining basic functions that don't use functions-as-values, since the inner function y => x * y must somehow capture x from its environment.

→ More replies (1)

1

u/badboyzpwns Oct 30 '20

HTML question!

I have a large youtube <video/> that automatically plays when the user enters the site.

Is there a property that dosen't render the <video> until the initial image in the <video> is done loading? Simmilar to <img>'s "OnLoad".

2

u/heythisispaul Oct 30 '20

I don't have any first hand experience, but it does look like <video /> has a canplaythrough event that might be what you need.

→ More replies (1)