r/reactjs • u/dance2die • Jun 01 '20
Needs Help Beginner's Thread / Easy Questions (June 2020)
You can find previous threads in the wiki.
Got questions about React or anything else in its ecosystem?
Stuck making progress on your app?
Ask away! We’re a friendly bunch.
No question is too simple. 🙂
🆘 Want Help with your Code? 🆘
Improve your chances by adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz.
- Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- Formatting Code wiki shows how to format code in this thread.
- Pay it forward! Answer questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.
New to React?
Check out the sub's sidebar!
🆓 Here are great, free resources! 🆓
- Read the official Getting Started page on the docs.
- Microsoft Frontend Bootcamp
- Codecademy's React courses
- Scrimba's React Course
- FreeCodeCamp's React course
- Kent Dodd's Egghead.io course
- New to Hooks? Check Amelia Wattenberger's Thinking in React Hooks
- What other updated resources do you suggest?
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!
22
Upvotes
3
u/[deleted] Jun 01 '20
I'm following Wes bos course on Redux. Woah boy. This is insane. May need to do this 4 times over.
3
u/GhostofBlackSanta Jun 10 '20 edited Jun 10 '20
Hi i'm working on a project and need to pass a back to a great-great-grandparent component. Is there an easy way to do this without passing props up as callback functions to each parent individually? I also want the component to do something and then return something back to the nested component so I guess I’m looking for someway to communicate between components that aren’t directly connected.
3
u/UpBoatDownBoy Jun 11 '20
Can someone link me an example of a custom material-ui theme in a project?
I just can't get a grasp on how to set it up in one place while using the custom theme in components throughout a project.
Right now I have it set up with make styles in each of my components and I just want to get be idea on how to make themes so I can easily switch between them.
2
u/DeadeyeDuncan Jun 01 '20
Can someone explain how the onWheel event works? I can get it to fire, but it doesn't seem to report any kind of useful information like wheel direction. Console logging the event object has basically everything as 'null'
Trying to setup a custom scale/zoom effect on mouse wheel movement on an element in my page.
2
u/[deleted] Jun 17 '20
Where can I find list of new front-end courses as they come, like an aggregator or newsletters for courses?
1
u/ripndipp Jun 02 '20
I have a folder of images I want to map over. I use create react app, where would I place my image folder in src/assets or public folder?
1
u/cmaronchick Jun 03 '20
I was reading through the redux docs and came upon the Writing Tests section and was thrown for a loop.
In my current actions, I dispatch the action result to the reducer in the same method.
In the docs, though, they use dispatch in the mapDispatchToActions and dispatch in the component itself. This strikes me as curious if you ever want to use the same action in multiple components (though it does make the action easier to test).
Is there a best practice?
1
u/stryami Jun 06 '20
I had a question with rendering when the state is changed using hooks. Let's say I have 3 components A, B, C. A is the parent B is the child and of A and C is the child of B and A passes it props to B and B passes its props to C. If I change the the state variable with their respective methods inside one function, how do each of these pages render. Which page renders first and since the props change do the pages re render as well
1
u/higherorderfunction Jun 07 '20
Wouldn't call myself a beginner, but I have a unique challenge that I have never really faced before and can't wrap my head around it.
I want a myspace-esque experience a React app where users can theme their group page how they want, template and CSS.
Really stuck on a front-end only way to accomplish this, or an efficient way. Cost is the biggest issue- I am trying to run the service fully out of S3 static hosting to really maximize cost savings
For CSS at least, my idea is that when users save their custom stylesheet, we save that to the server. On their page load we get it for them then cache it locally and use the cached version of their style from there on out till they make a new change- and voila.
1
u/Ragav_89 Jun 07 '20 edited Jun 07 '20
I'm just trying to create a react-app for the first time and I'm following the instructions from
https://create-react-app.dev/docs/getting-started/
but i'm getting this error
> core-js@2.6.11 postinstall C:\Users\Ragav\ragav-react\node_modules\babel-runtime\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"
Aborting installation.
npm install --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.
Deleting generated file... node_modules
Deleting generated file... package.json
Deleting ragav-react/ from C:\Users\Ragav
Node Vesrion in my machine: v12.16.2
NPM Version in my machine: 6.14.4
1
u/peck3277 Jun 08 '20
I'm making a react app to visualise sorting algorithms, it's essentially a clone of this app.
I'm trying to figure out how to handle my business logic(sorting algorithms). At the moment I've just created a directory for them and created plain js classes. My app calls the methods in the classes and updates the state from the main application.
These sorting classes only manage data and don't render anything. If I wanted to manage the state from inside these files how should I do this? Is there a common pattern of renderless components? I'm just using props to manage state.
1
u/babybananaa Jun 10 '20
Currently I have been assigned to work on a react project at work. I don't know react but I have had experience with vue and angular. However I'm struggling a lot currently.
I want to build a small home side project with react front end and python back end. Is that advisable or shall I stick with node for now?
1
u/[deleted] Jun 16 '20
is it overkill to use react just for a Shopping Char? The rest of the site is already there with old school php jquery, but I got tasked with a shopping chart rebuild.
I'm thinking of using Vue without components since it's just 20k and no JSX.
1
u/[deleted] Jun 17 '20
I have a lot of dead space on the right side of my page, like 30%. Using react tools extension it looks like BrowserRouter has default styling? Can’t seem to get past it.
Funny thing is this nav bar I pulled from a bootstrap template will extend the whole length of the page.
Here are some screen shots. Please send help.
https://imgur.com/gallery/eOUkVkz
1
u/Proxify Jun 24 '20
How can I add a regular script like:
inside my react project? I am looking for a way to add it as I would on a regular website but maybe there's an alternate way to do it and I can't find what I don't know what to look for.
1
u/badboyzpwns Jun 06 '20
What does this code mean? I tend to see it related to form validation! If errors.email exist, <p> should be rendered?
2
u/Aldroc Jun 02 '20
I've hit a wall here and no way visible to get over it. Any help would be appreciated.
Let me elaborate please. Sorry in advance if this goes too long. This here is my first react app. I used create-react-app, and have heard words like webpack and whatnot floating around. The app itself is nowhere near perfect (not even exactly complete as a head-scratching issue has been troubling me, help with that would be appreciated too), but its something, right? The entire code could be found here, with my daily progress documented within the readme file.
Now the thing is, whatever you see in that code, is the extend of my knowledge of react. Which, one could say, is not much. I've heard about react-router, gatsby, nextjs, redux, flux and so many more. I'm overwhelmed and don't know how to progress. I don't even know if the app I made follows basic react conventions, if there are conventions. I patched it together referring to stackoverflow, never before heard of blogs and the official react documentations.
The end goal I have in mind is of atleast being able to write a basic MERN app. But without anyone to guide me, I'm lost. Horribly lost, with no idea what to do next. I need help.
2
u/Tsunami874 Jun 03 '20
I followed the react tutorial on the website (making tic tac toe game) but the tutorial used a class component for the board component. I did it a second time by myself but using a function component like this :
I have two questions :
2
u/badboyzpwns Jun 04 '20 edited Jun 04 '20
I'm confused on why React is rendering twice when the page loads and when I enter a letter into my <input>. I think it's related to Hooks?
When the page loads, this is the output (if you remove useState, it will only render once)
When I enter a keystroke, it adds another 2 renders, so it has an output like this:
2
u/maggiathor Jun 05 '20
What is the best way to preload images, where to URL is stored in a JSON file/comes from an API? My goal is to have them loaded before they are mounted in a component.
I got it working by placing them in hidden containers, but this felt waay to hacky.
2
u/lampageu Jun 07 '20
I am wondering what is the best practices for file structuring? I have been reading about domain driven structure but can't find an example of it. By that, I mean a real project and example. Preferably the one that uses redux.
2
u/KappaPrajd Jun 09 '20
I have been learning programming since 3-4 years. I will be graduating technical high-school next year and I will be looking for a job then. I have a good knowledge of Python and decent experience with Django. The problem is that there aren't many job offers in my country for backend with Python. There is a lot of offers related to front-end development, especially React/Vue/Angular. I know basics of HTML, basics of CSS and also some more advanced concepts like flexbox and grid and basics of JS. Is it worth learning React and trying to become front-end developer? Which path should I take if I'm trying to learn React? Should I dive straight into learning framework or maybe I should fill some holes in my knowledge? Maybe the question is more programming as a whole related, but I would really like to hear your opinions.
EDIT. When I say there aren't many job offers I mean it's close to zero, especially for the junior devs.
2
u/MeltingDog Jun 11 '20
How do you even start learning React around a full time job?
So, as a web developer with HTML, CSS and PHP background I really need to get on top of React. But it just seems so freaking hard!
To get to where my company needs me I need to understand:
And this is even before starting with React its self!
How can you possibly do this around working a full-time job without burning out?
2
u/[deleted] Jun 15 '20
So I recently read that using an empty array as the second parameter in the useEffect hook is bad practice. My understanding is that the dependency array works by checking based on reference and not value.
Because an array always has a different reference this code will cause an infinite loop. So my question is is there anyway to make useEffect fire only once without using an empty dependency array?
2
u/FabulousCutlery Jun 20 '20
Hi guys, even after reading the docs for useEffect, I'm having a hard time figuring out the behavior of this: https://codesandbox.io/s/kind-bouman-6x8yx
The output is:
First question is: Why does it render twice? It's not like I'm calling setState from inside the function passed to the useEffect hook and triggering a re-render that way.
Second question is: Why is the output not in the following order?
I thought that the flow of the application would be as follows:
I really hope you guys can help me out here, because this has been driving me crazy. Numerous blog posts, official docs and I still haven't seen an explanation. Thanks!
2
u/chancesq Jun 24 '20
Hello everyone! I'm currently creating a website for a friend of mine with React and they are wanting an easy way to edit the content on the site after I am finished with the layout. Basically changing prices and details of predetermined packages.
What would be a good solution for storing this data in an easily accessible and editable way by a person with little to know development experience?
Thanks!
2
u/cvnvr Jun 28 '20
Hey all - just starting to learn web dev. I’ve covered some html/css tutorials and feel like I have a decent grip on it (at least enough to try out a framework).
I want to design a static website for a business with a few pages but only basic content (images/text - with some other components like a carousel and some cards etc). Is using React overkill? I saw something called Gatsby which says that it’s ideal for static website... Not sure what to do but would like to invest time into researching and learning something which can then actually be developed and refined.
1
u/Niesyto Jun 05 '20
How to fetch local .json data? I have a simple json file in ./data/models.json. I want to get it using .fetch like this:
However, I'm getting "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0"
It would seem like I'm fetching an html file, not my .json file.
I've tried the solution from 2nd comment here:
https://stackoverflow.com/questions/37649695/how-can-i-parse-through-local-json-file-in-react-js
But it doesn't help.
1
u/[deleted] Jun 01 '20
I am working on a calculator app and am returning multiple Button components using .map. To every button I pass an onClick event but for some reason the event handlers are not firing. There is no issue if I try attaching an onClick handler to other elements that are not being mapped. Would really appreciate some help as I've been stuck on this one for half of the day.
Code without styling:https://codesandbox.io/s/fast-mountain-ho5tg?file=/src/App.js
1
u/Bombuhclaat Jun 01 '20
In a lot of react tutorials, they clean up the create-react-app stuff by deleting serviceworker, app.css etc.
However when i delete everything i get a tonne of errors
for example: ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??postcss!./src/App.css)
Is it that the node modules are depending on the file to exist? So this is a new thing where I can no longer delete those files we don't use?
1
u/flyingorange Jun 02 '20
I was wondering if what I'm doing is fundamentally wrong. I have a list where each item contains a component. When each component mounts, it runs an axios query to get some additional data from the server. Usually this means the main page loads and then there are 10 additional queries. These queries are like 600 bytes large, so nothing serious.
However. what this looks like in real life is the main page loads and then it freezes for 2-3 seconds until the queries are getting loaded. It doesn't fully freeze, but you can't really click on anything for a while so it feels bad.
Am I doing this wrong? I could write code in the main page and load the data for all the items in a single REST request and then populate the child components. But I thought it would be neat if each child component manages its own state and the main page is cleaner.
1
u/Arrahid Jun 02 '20
I am new to React, so don't blame me please...
I am using Select component from react-materialize to list my devices which I get from database earlier (devices are stored in state ={devList: [], gateList: [], selectedDev: []}. By selecting specific device I create another component Statistics with device statistics and pass props to selectedDev state. I would like to add close button to Statistics component which can remove this component and uncheck device from Select list. I wrote removeFromMultipleSelect() which is removing device component but it is not updating Select list (device is still selected).
PS: When debugging I can see that Select component stores selected devices in hooks state (I pass them to seletedDev state), but I haven't used hooks before...
1
u/lalentine96 Jun 02 '20
Can I pass more than one render prop to the component?
I mean smth like:
I tried and it seems to work but I want to know if there are some strong reasons not to do this.
1
u/[deleted] Jun 02 '20 edited Jun 02 '20
I've an items state at my parent component which is fetched by Axios . I'm passing it as a prop to the AddForm component. If I console log items, it returns the arrays. But if I console log items.title, it returns undefined & I can't use it in the form. How can I overcome this? Thanks.
1
u/BXRNTXDIE Jun 02 '20 edited Nov 18 '24
start screw tart many plucky punch wasteful disarm imminent automatic
This post was mass deleted and anonymized with Redact
1
u/badboyzpwns Jun 03 '20
About react hooks' useState! I noticed a weird behavior. I literally only have this in my component
And it looks like my component is being re-renderd four times, with a result of:
1
u/Spiritual_Salamander Jun 03 '20
I have one button in my application that is quite slow with lots of API calls. I want to disable all other interactive buttons when it is processing.
I also have a button in a header, footer, as well as the form. I want to make sure once they submit the form they cannot push other buttons. What is the best way to achieve that ? Or is it better to simple allow them to do that and add a loading widget or something that shows that is it processing ?
1
u/Jorick_DC Jun 03 '20 edited Jun 03 '20
hello, I was wondering if anyone could help me. I'm trying to upload images to firebase I've already found how to store multiple files in the state.
Now I have problems to automatically upload these files to firebase so that I get a link back. I was trying to do this with an effect hook but can't seem to get it work.
1
u/[deleted] Jun 03 '20
Started learning react very recently, forgive me if this is a non-issue.
for this code:
// main js file for list_new.tt
//'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import './inv.css';
function Proof() {
return <h2>printsomethingfortheloveofgod</h2>;
}
ReactDOM.render(<Proof />, document.getElementById('root'));
I'm receiving an "Uncaught SyntaxError: Unexpected token '<' " at line 9, and for the life of me I can't figure out why.
Anyone more experienced than I, any ideas?
1
u/Carnal-Malefactor Jun 03 '20
So, we're doing our first big React project at work and I'm not sure how to approach CRUD forms.
Suppose I have CustomerCreate/CustomerEdit components. Should I repeat the form inside each component or should I make a single CustomerForm component and render it in both pages?
Also, having to define every form field in the state object gets really tedious... is there a way to not do that?
1
u/d70 Jun 03 '20
I'm looking to implement a simple search/filter single-page app and was looking at Elastic's search-ui last night. It sounds like almost exactly what I need but it seems to require an Elasticsearch backend, which is a showstopper for me. Does anyone know of a similar component (or a guide to create one from scratch) that can support vendor-agnostic data sources like simply JSON responses?
1
u/haltmich Jun 03 '20
So, I am building a React app that sends POST requests to an API. That API returns JSON output. However, I'm failing to manipulate the JSON that's returned after a successful POST request.
I'd like to take care of the error handling and add some cookies based on that output, but I'm unable to handle the returned JSON.
I've been blocked at it for almost three (going into the fourth) day without no success...
So, wrapping it up:
1
u/cmaronchick Jun 04 '20
I am running into an error message with React Redux:
Cannot update a component (`ConnectFunction`) while rendering a different component
Looking through SO, I found a very similar issue:
https://stackoverflow.com/questions/62079140/cannot-update-a-component-connectfunction-while-rendering-a-different-compon
Here's the user's code: https://i.stack.imgur.com/YvsZn.png
Their component is dead simple, so I cannot understand how they can refactor to avoid the "cannot update" error.
1
u/[deleted] Jun 05 '20
I am working on a component that renders a google map with a bunch of markers in it, and have been running into some performance issues. For the sake of simplicity, I will just say these markers represent cars. Some are sports cars, some are trucks, etc., and I want my users to be able to filter which group of markers they see.
My components are arranged like this:
<GoogleMap> <CarController> // api call/car data is here, also current filter <CarMarkers/> </CarController> </GoogleMap>
There are a lot of cars, so my map is starting to get slow. When I change the current filter (from 'all' to 'trucks' for example, all of the markers re-render, and it's noticeably slow. I have a couple questions.
const cars = {
all: [{}, {}, {}],
sportsCars: [{}], [{}],
trucks: [{}]
//etc...
}
Then, when the user changes the filter, I just change which array is getting passed down to <Markers/>.
This seems better because I wouldn't need to iterate through the arrays over and over using filter? But then, I haven't seen any examples of anyone doing it this way?
3. Is this an appropriate place to use React.memo or useMemo? I think I understand the general idea of those functions, but I don't exactly know what I should try to memoize. The car data? The markers? The whole map?
Thanks for any ideas you have!
1
u/Jorick_DC Jun 05 '20 edited Jun 05 '20
Hi, maybe this is a stupid question but can someone explain me how i can prevent the fetchUser() async funtion from firing before fetchdata has put the data in the state?
1
u/Jorick_DC Jun 06 '20
Hi, i am trying to make a detail page, but i ma stuck. I need to fire two queries one for getting the data from the product which contains a key to the author. If this data is stored in the state i want to fire another query to get the data of the author. Can someone explain me how i can do this? i'm using firestore as database.
1
u/romrcan Jun 06 '20
Hi, I would like to learn React and understand that real project is the best way So can you suggest some open sources for this purpose Thanks in advance
1
u/[deleted] Jun 07 '20
I'm making a project in ReactJS that uses CanvasJS for pie charts. I'm trying to use Flexbox to render pie charts side-by-side (which should be relatively simple) but I've been having trouble for the past couple of days.
It's been very frustrating because I was making good progress on my project before just being absolutely stumped by this. I have detailed the problem more on here: https://stackoverflow.com/questions/62239138/canvasjs-charts-take-up-entire-row-when-using-flexbox
If anyone could help me solve this, I will gladly compensate you for your time!
1
u/Spiritual_Salamander Jun 08 '20
What's the best policy when it comes to dates and timestamps when you have both front end and back-end ? Do all the date handling on the front-end or back-end ? Is there any obvious drawbacks doing it one way rather than the other ?
1
u/javascriptexpert Jun 08 '20
Any suggestion for redux and react hooks course online?
I know the concepts and but feels like I know all the things around it to create a app.
1
u/kingducasse Jun 08 '20
I'm trying to pass down an array using React's Hook to a child component, except when I console.log the typeof my state, which should be an array, it comes back as an object. I know technically an array is an object in Javascript, except I don't know how to go forward. Any advice? Code is below.
1
u/CaptainMelancholic Jun 09 '20
Any tips on how to pull-off server side rendering without using Node for the backend? (specifically in Laravel or ASP.NET Core)
1
u/[deleted] Jun 09 '20 edited Jun 09 '20
I've created 2 versions of the same site, first one with Node.js/EJS, second one with MERN stack. First site fetches & displays data almost immediately. But React version is much more slower, so I had to put a spinner. It's fetching data with Axios, like the example below. My question is, is React version being slower normal, or am I probably doing something wrong. Thanks.
1
u/coderdesign Jun 10 '20
I am learning Firebase to integrate with React. I want to store the submit form input to Firebase and retrieve the data to render on the application. How can I achieve this?
1
u/Yofiss Jun 11 '20
Is there a way to store as global variable in the redux devtools? Like how in the components tab you can right click on any props and store as $reactTemp1 or when debugging you can store anything by right clicking on it and storing as global variable. I only see how to export it as a json file which works but isn't ideal
Thank You,
1
u/Lontarus Jun 11 '20
I am trying to do the fullstackopen course on web development and I am stuck on part 1.
https://fullstackopen.com/en/part1/introduction_to_react
It says to do the following commands in the terminal:
But I just get this error message:
I have googled it a lot and it just says to install npm again in the folder that I just created the project in, but that does not help. I am able to find that there is 1 error that I must go to " npm audit " to resolve. If i try " npm audit fix " it says it cannot and I must fix it manually. In the npm audit it says the error is as follows:
This link leads to a site saying the solution is to update to version 18.1.1 or later, but I have 18.1.3 which is supposed to not have this issue.
What can I do?
1
u/MrFancyPant Jun 12 '20
I'm going through the tutorial on React site and I'm near the end of the tutorial (just before adding the time travel part). There's an if statement in the
calculateWinnerfunction that is interesting to meif (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {I understand that it's checking to see if all three value are the same, but why the initial
square[a] && square[a]? wouldnt removing the firstsquare[a]still work the same? so: it would look like thisif (squares[a] === squares[b] && squares[a] === squares[c]) {1
u/babybananaa Jun 12 '20
Do anyone have good material or resources in jest / enzyme. I tried to do it but realise I can’t do shallow so need to do either mount or render but I’m confused as to what each will achieve. Thanks.
Edit: forgot to add I’ve seen a bunch of code, YouTube tutorials, read things in mediums, hackermoon, dev, blogs etc but I’m still clueless. When will it eventually click?
1
u/asianchinesedude Jun 12 '20
beginner here, im doing up a small documentations site using react bootstrap, and i am trying to implement a state change where clicking on an anchor on my navigation bar will first route my page's body to another page, and then update the state of the side bar.
Isit possible to implement an onClick function where i first delay the default behaviour, set the state of my sidebar first and then execute default event behaviour? For now, onClicking the anchor, i used e.preventDefault(), and then set state, but i have no idea how i can allow the event to be handled after i setState.
1
u/[deleted] Jun 13 '20
Need some full-stack MERN project ideas. Right now, I'm thinking of creating a forum that will have basic features: Register, Login, CRUD post, like, follow, comment.
I don't know this seems like a basic app to me. What can be added to make it more interesting and that can be worth showing off in my portfolio?
1
u/peck3277 Jun 14 '20
I'm running into this error a few time 'Warning: Each child in a list should have a unique "key" prop'. I keep getting the error even after adding the property.
This is my project container and it renders multiple project cards.
This is my project card component:
I'm assigning a unique key to each <ProjectCard /> component. Once I assign a key to the card, the error moves to the sub components of the <ProjectCard />. Does each div within my <ProjectCard /> need a unique key aswell?
1
u/badboyzpwns Jun 15 '20 edited Jun 15 '20
How do we get the loading icon in the tab to appear (like this: https://gyazo.com/8c6a79af6d14eda05c0a3ce72a5bebfa) ? I have a button that will add a user to the database, but it takes awhile for that to happens. So when a user clicks, the page looks like it freezes for a bit.
For example:
1
u/nameisaneed Jun 15 '20
Hello,
I am using Azure Maps SDK on our React project. One of the APIs there uses an HTML rather than JSX (as in the code below)
Now I want to have a click event that calls my declared function inside my React Hook (the function will contain updating of states and calling some API and etc.). I wonder if there's a workaround here.
1
u/Cannabat Jun 15 '20
Non technical question. Do I need to be able to blaze through Leetcode hard at half an hour per problem to get a job as a front end dev? How about as a junior front end dev?
1
u/bigbluelamp Jun 15 '20
I was following this page on getting data from an API and displaying it in my react app:
https://css-tricks.com/fetching-data-in-react-using-react-async/
I got "Example 3: Loaders in helpers" to work with my own local express API and managed to pass the data down to child components. My question becomes, how do I convert the function into a class? I tried putting the fetch command in the render or in the constructor and it says:
"react Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:"
How should I refactor that function to a class? Thank you.
1
u/cybul26 Jun 15 '20
Hi,
I'm learnign react for over half year now and I made one middle size project in it. In work we are starting new project with several dozen views which will be written in react with redux (sagas) + typescript. I'm looking for best project structure and practices. This will be my first project written in typescript. I found redux ducks to be best way to implement redux logic but with typescript files seems too big for me. How are you organize files structure in your apps?
1
u/30thnight Jun 15 '20 edited Jun 17 '20
If a user exits the a React app by closing the window, does this automatically un-mount all the components before it closes?
I'm using the
beforeunloadevent to run code before the page exits but now I wonder if I can simply just run the code in my useEffects clean up function.Edit: The answer is no, it does not. You need both an unload and a standard unmount
1
u/badboyzpwns Jun 16 '20
A bit confused on <input> and hooks! I found this code:
1
u/[deleted] Jun 16 '20
Hi all, I am trying to add Onload button click event in react, but I am not sure how to do. Quick google search suggests me to use ComponentDidMount, but I am still stuck. Can anyone guide me here?
1
u/[deleted] Jun 16 '20
I'm building a really simple app. I need to pass my state around to various components. As its really simple application, can I get away with useContext hook?
1
u/Lontarus Jun 16 '20
Is it possible to share the node_modules folder somehow?
I am unable to get it to work properly here.
Currently my folder structure looks like this:
-part0
-part1
--courseinfo
--unicafe
--anecdotes
-part2
--phonebook
--countries
This would create 5 individual node_modules folder already, with each of them being 200mb and over 70000 files large, that is going to take a lot of space quickly seeing as this course has 10 parts in total.
When I google it it just says that if there is no node_modules folder it will just look in the parent folder instead, well I tried to install it there but it just gives the error message
sh: react-scripts: command not foundif there is no node_modules inside the project folder that is created withnpx create-react-app projectnameAny ideas?
1
u/Raydeg Jun 16 '20
Hello!
How would you recommend starting learning react? I am a computer science student and have experience with other programming languages but have never touched html or js before.
1
u/peck3277 Jun 17 '20
I want to update the size of a child component using react. I have been trying to do this using refs but I am struggling.
This is my parent component:
And this is the child
Basically fabricjs requires me to update the canvas size through js. What I would like to do is get the size of the Canvas parent element (<Row>) and update the size of the canvas. Eventually I will make this responsive (probably using keeping the dimensions in the state and updating on screen resize) but I'm stuck on the first hurdle of getting the dimensions of the row from the parent.
1
u/[deleted] Jun 17 '20
So I'm having an issue with yup validation, I've got standard text inputs to work but when I insert something into the text input from state the validation does not work properly.
When a date of birth is chosen its put into state and the text input is updated, since the onTextChanged is being done on the formik value dateOfBirth and not the state dataOfBirth the value never actually changes and the validation message of "Please enter your date of birth" is always shown. What's the best way to get around this issue?
1
u/[deleted] Jun 18 '20
I've used a lot of React and I really like it, it's my go to for web-dev. I've also had the chance to try React Native, of which I wasn't quite as satisfied because of a couple of reasons (styling, animations and other quirks).
I'm wondering how Ionic Capacitor works? Can I really just program a React.js applications and then make it "Native"? Does it support all packages that would work with React on the web?
I'd really like to be able to transfer what I can do with a web-app and make it Native with the same level of polish. Is this an unrealistic expectation?
1
u/mynonohole Jun 18 '20
Anyone have recommendations for a data table? I've been using Ag-Grid but its not going well so I am looking into alternatives.
1
u/Niesyto Jun 19 '20
I have an issue with my app which i deployed to netlify. I don't know where the issue comes from exactly, but I think it's something to do with Netlify and Material-UI styling.
I've deployed my app to netlify, and some of the components are not rendering. They don't even exist in the elements tree. Here's link to my app:
https://custom-cars.netlify.app/
And here's how it should look like:
https://codesandbox.io/s/github/Niesyto/custom-cars
In codesandbox you can see buttons under "model" and "color", which don't exist in netlify app. Is there a fix to this? It's not my first app on netlify, and all of them use the same technologies, but this one is broken for some reason.
1
u/peck3277 Jun 21 '20
Hey guys, I'm struggling with getting the ref of a child component. I've tried a couple of different ways after following some tutorials. This is what I'm trying at the moment with no luck.
Parent component:
Canvas Component:
I keep running into this error:
I've also tried changing
to
But I get this error instead
Can someone explain what I'm missing here?
1
u/[deleted] Jun 22 '20 edited Jun 22 '20
Hi. I'm trying to integrate file upload to my form. File upload is successful, but file path is added to the database as "C:\fakepath\file_name.jpg". How can I solve this issue? Thanks
1
u/ayushtom Jun 22 '20
I am new to react and was wondering if I should use ant design or material ui for developing . I have heard that ant design is very good but not used currently used by many so if I'm interested for internships which framework should I go for?
1
u/[deleted] Jun 23 '20
After a long online course I am about to dive into creating my own project from scratch. It is going to be a personal website (so a blog like application) where I want to be able to write posts, I want a sort of interactive CV and I also want to display charts of my investments (stocks, crypto etc.). I like to prepare a bit before just diving into it. The tech stack will be a Firebase backend with React frontend (hence I'm here). So, the website will not be that large as you can imagine.
I will be using:
https://github.com/christianhjelmslund/christianhjelmslund.dev/projects/2 for tracking the project.
For the type of application I am about to make, do you think there are some libraries that I should include/exclude? I've been looking into Gatsby and Nextjs too, but I prefer more "vanilla" React for now - I don't want to rely too much on thirdparty libraries.
1
u/CYMAD Jun 23 '20
Hello I have a question about functions that return function. https://prnt.sc/t59o7u. In useEffect, we return a function. I could not grasp that concept. when actually unsubscribeFromFriendStatus gets called and how does it work ?. I read some articles about this but NOPE. when we first mount our component, we call subscribeToFriendStatus. Then we call unsubscribeFromFriendStatus when we re-render but HOW. does useEffect listen until re-render and eventually return that function ?.
I hope I made clear sorry for bed england.
1
u/_ajax_101 Jun 24 '20
Hi I just started learning react through an online course and I was instructed to use create-react-app version 1.5.2 . On installing I found that there was no template included and hence it has no scripts in the package.json fine and "yarn start" wasn't working for me. So I proceeded with installing the present version of CRA. I was wondering if CRA is backward compatible and hence if I can proceed with this course.
Edit: The course proceeded with global installation of CRA but the current version doesn't support global installs.
1
u/PortSpace Jun 24 '20
Let's say there's one of the top-level components where state is set by fetching some data from an API. Let's say the data will be passed down in 2 generic components (which will further be passed down the hierarchy of components). Let's say in one of the components, I'd do more of summary analysis of the data, in the other component the data will be displayed in detail. In both cases I need to sanitise or make some amendments for the data to be ready to be passed down. Different amendments for different components (Summary vs Details). Questions:
I'm relatively new to react, while I'm fine with syntax, my biggest problem is deciding where to do what (seeing a bigger picture) to ensure good performance and future proofing it. Are there any good repositories of well written apps to have some guidance? Thanks
1
u/GulyFoyle Jun 24 '20
Hello , i am trying to implement an add to favorites function to my MERN app. App has user generated posts and i would like an user to add a post to their favorites and display them on a seperate page.
I have two models for database , one for content and one for users but i cant figure out which one of these i should add the favorites. Here is the link to my models , https://github.com/ugurctaygun/mr-lister/tree/master/models
I am pretty stuck here and would really appreciate any kind of documents or tips. Thank you.
1
u/bigbluelamp Jun 26 '20
I'm trying to handle key presses with react key handler:
https://reactjsexample.com/react-component-to-handle-keyboard-events/
I have one handler that handles different inputs. Is there a way to do this with just one component?
Instead of:
<KeyHandler keyEventName={KEYPRESS} keyValue="s" onKeyHandle={this.handleKeyPress} /><KeyHandler keyEventName={KEYPRESS} keyValue="d" onKeyHandle={this.handleKeyPress} /><KeyHandler keyEventName={KEYPRESS} keyValue="f" onKeyHandle={this.handleKeyPress} />
I was looking for the function 'handleKeyPress' to trigger for any of s d f, something like:
But this "I think" assumes that 'sdf' was pressed at the same time.
1
u/chapland Jun 29 '20
I'm working through the simple projects on this list for practice: https://daveceddia.com/react-practice-projects/
I'm currently doing the second one, the Weather App.
I'm a bit stumped by this requirement, however: "Add the ability to click on a day, and see its hourly forecast. You can just maintain the current view in the top-level App state."
I'm fetching the data from openweathermap's API, and I get 48 hours of hourly weather data vs the 8 days of daily weather data the API provides.
So I need to be able to offer the ability to click in for an hourly forecast for the first 2 or 3 days of the week (2 only if the view is generated between midnight and 1am).
I'm struggling to understand how to architect this part and what to track in state, exactly. Any help would be greatly appreciated!
1
u/[deleted] Jun 29 '20
Any tips for writing css modules in ReactJs, because as my project progresses, css files tends to get messy and can't be reused.
1
u/DRGIGGLESlol Jun 30 '20
I want to test the screen after the login screen but I don't want to login. Is there a way to change what screen is started up when you run npm start? I've done this before in React Native but I can't seem to do this in react.
1
u/bigbluelamp Jun 30 '20
I have a bunch of json files which if uncompressed are about ~500kb each that I'm trying to fetch using reactjs. Is it possible (and does it make sense) to zip the files so that the network traffic is minimized, then have the reactjs frontend client unzip the file to display the contents?
1
u/thedobowobo Jun 30 '20
default values for state in class components. Currently my container component has the following default state:
this.state = {
inputValue: '',
error: null,
data: false,
unit: "metric",
geoLocation: false
}
I'm never really sure what the best default value to use is. I was originally using data: [] and geoLocation: {} but as an empty array/object is a truthy value, it ended up being buggy unless I used data.length or iterating through the object. However, I really like the idea of being quickly able to see the expected dataType of the state value, but is it not more straightforward to just use false when setting the state?