r/reactjs • u/dance2die • Jul 01 '20
Needs Help Beginner's Thread / Easy Questions (July 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
- and these React Hook recipes on useHooks.com by Gabe Ragland
- 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!
35
Upvotes
3
u/aidenight Jul 12 '20
There's a reason to use a library for styling (like styled-components or Material UI) instead of use pure CSS in a React App?
I've seen this options and wondering (in my newbie thoughts) if is not more straightforward just links a CSS file in my public HTML.
3
u/Flash-1 Jul 15 '20
I am doing a simple react weather app and i keep getting this error when I try to fetch a cities weather "No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." not sure what to do since anything I do does not help. i checked stack overflow but nope.
2
u/nyamuk91 Jul 02 '20
What is the general opinion (in 2020) of Class Component? Should we try to avoid it? Or is it completely fine to be used?
2
u/[deleted] Jul 06 '20
To precurser I'm fairly new to both backend and more so react.
How does authorising users work with react? In the past I would feed my routes from my backend with nodejs and so I could use middleware to protect a specific url. However with react I can use react-router which would bypass the backend authentication?
How would I implement jsonwebtoken to protect routes that shouldn't be accessed until logged in?
Thanks.
2
u/babybananaa Jul 26 '20
I’ve finally completed a YouTube tutorial on react hooks and I don’t know if it’s useful for people if I tidied it up made it pretty for people to refer back to. It explains what each one does and how to do it in very simple terms definitely aimed at beginners more than anything. Or is there millions of these things around? I originally did this tutorial to learn more about react hooks rather than doing it as a tutorial for other beginners.
4
u/[deleted] Jul 24 '20
As a newbie how can I judge whether the state of my application will be complex enough to warrant the use of Redux or I should just use the tools provided by React?
I plan on building an issue tracker/ticketing system of sorts and just can't decide if I need it or not.
Part of me wants to make use of it so that it boosts my chance on jobs that require knowledge of Redux. On the other hand I'm afraid of looking stupid if Redux ends up being overkill for my application.
1
u/[deleted] Jul 11 '20
Hey does anyone have an example of integrating the iOS calendar with your app for appointments? I am using the react-native-add-calendar-event library but I am a little lost as to the implementation and can not find much in the way of help online. Thank you!
1
u/backtrack432 Jul 20 '20
I'm building a command line like Superhuman or Spotlight Search on Mac (cmd+space). How should I mimic this component (keyboard shortcuts, open/close command, autocomplete suggestions, dropdown mechanics)?
1
u/thesurething Jul 20 '20
Is there are way to have a timeout on a prop?
For example, if I have a user prop populated by a fetch request and sent to a child component. If the child component's prop is still null after 30s do something?
const Child = ({user}) => {if (!user) return "fetching..."// after 30sreturn "there was an issue..."}1
u/fpuen Jul 24 '20
Do you guys have any tips on how to tightly annote JSX components beyond
JSX.Element?JSX.Linkbelow didn't work:1
u/reppytile Jul 26 '20 edited Jul 27 '20
Edit: I just remembered using this project before https://github.com/crabbly/Print.js and it looks like it (sort of) is an example of what I'm talking about. I believe this will be a decent starting point for me. However, if anyone knows of any better ways to get started with what I want to do (see below), let me know. Thanks!
Hi everyone!
I have used React.js in a few demos and also for a sort of "single page app" scenario. I really love working with it it.
And now I am curious if it is possible to bundle a bunch of modules and export it to a single file that can be used by any website that I choose. My (admittedly) naive understanding is that all of the JavaScript dependencies are bundled together and intended to be served as single file.
For instance, say I import React.js, and then a module for handling modals, and a module for displaying a loading icon.
Is there any reason why I couldn't share this file between several different websites? I have looked all over for examples of someone doing this, but only find people creating full fledged apps and modules to be imported by other React.js apps.
For what it's worth, I reallllly want to lean on React.js' ability to quickly create user interfaces. Otherwise, I'm stuck doing it the old document.createElement("div") etc way.
Am I barking up the wrong tree here? If React.js isn't the answer, is anyone aware of a better solution out there that suits my needs?
Thanks! :)
1
u/fpuen Jul 27 '20 edited Jul 27 '20
Do you guys have any slick ways of returning a component from json data without having to use a case or if statement set? JSON can't hold JSX components.
Say you're starting with a string that is the exact name of the component you want. What can be done to convert it to a JSX component?
Edit: Saw on SO that the old ES5 way works. i'll use that for now. If there's a JSX way please let me know, thanks.
1
u/monosinplata Aug 01 '20
Here's a video I made on how to create a User Registration Form with react-hook-form: https://youtu.be/mrTPrbSoAx0
3
u/OpenSourceObsidian Jul 04 '20
Just started Maximilian Schwarzmuller/Academind course on Udemy and I was wondering: does he uses hooks through all of it or does he only implements them at a later moment?
3
u/PortSpace Jul 23 '20
Are there any good github repos with medium difficulty react demos using hooks? The ones I've found are either very simple (todo list), written in Class components, or various libraries for react (not website/app demos). I'd like to see some good practice. It's one thing to read the documentation / tutorials but it's entirely another thing to implement good organisation/logic, etc. in a real project. I thought it'd be beneficial to see some good react in action. Thanks
2
u/Jonyface Jul 03 '20
My app consists of one page and I am using firebase for the backend. On first visit, I want the user to be a Firebase Anonymous User until they want to sign in with google. How do I manage the current user? Do I keep the user object in the state?
2
u/nyamuk91 Jul 04 '20
I have a few more questions:
2
u/Derpstiny123 Jul 07 '20
what's the most popular way of writing css/sass in react with nextjs? Currently using styled-jsx.
2
u/hurrdurrderp42 Jul 08 '20
Do i still apply to job offers with 2+ years of react, when i have 0 commercial experience?
I have tried to move away from just html/css, have a decent github with multiple react apps, still can't land a job. I don't understand how do people start out with react, when all i see are 2+ years of react and redux.
2
u/unordinarilyboring Jul 11 '20
I can't seem to figure out a font problem. I am setting for example: font-family: "Asap SemiBold" which works fine in chrome and firefox, but is not applied in safari. What does seem to work in safari is setting font-family: "Asap" and font-weight: 600 though. Any ideas why safari won't pick up the weight names?
2
u/sGvDaemon Jul 16 '20
Site here <<
On my website I use an animation to rotate the screen, however it only maintains its shape if I change the height to static when the screen is rotated. This allows the site to work properly while tilted but everytime I click the menu button it resets the page position back to the top of the page. Is there any good way to prevent this from happening? Do I need an event listener to track where the user always is, or should I rethink how I handle the angle/tilted content?
2
u/CYMAD Jul 17 '20
Hi, I have a question. What do you guys prefer for authentication in backend when you work with React? . I work with express, jwt based authentication but after setting cookies "res.cookie()" I am not able to get setted cookies in another route req.cookies[ ]===undefined. how am i gonna solve that issue.
2
u/wilecoyote42 Jul 24 '20
Hello:
I was reading the page on React's docs about State and Lifecycle:
https://reactjs.org/docs/state-and-lifecycle.html
And I don't understand why you can pass a function to "setState" to make state updates synchronous.
In other words, according to the docs:
this.setState({ counter: this.state.counter + this.props.increment, });
Might update the counter when it's executed... or it might not. But this:
this.setState((state, props) => ({ counter: state.counter + props.increment }));
Will always update the counter. Why? What does React do internally in that case? Does it execute the internal function first and then store the result to update the state later, when it's better for performance? Or does it update the state inmediately? And in that case, is that a good practice for performance? Or does it do something completely different?
2
u/reactyboi Jul 30 '20
I have a component that can throw lots of unexpected little errors, and I want it to return
nullif an error occurs.Wrapping the internal logic in a try-catch has done the trick, but it feels incorrect somehow since I have never seen someone do this before.
Could I achieve the same result with an Error Boundary? If so, do I wrap it around everything, or do I put a Boundary around every component that I feel can throw unexpected errors?
1
u/LordofCookies Jul 27 '20
Not sure if it fits here but here it goes:
I would like to develop an app that has a dashboard (mostly to practice styling and React in general) but I'm not sure if there's any API with that type of info for me to work with. I would like to create charts and graphs with the info provided by the API but I think I'm failing to encounter the APIs I'm looking for
1
u/noughtme Jul 01 '20
Any good introduction to React site architecture? Right now I’m working on a multi SPA portfolio site and trying to figure out the best code sharing and state sharing strategy. Webpack 5 module federation looks like it might solve my problem, but then I might need Redux. Maybe a monorepo might be simpler. Should I split out UI and login components into an NPM library? What is Lerna? Should I import shared components at build time or run time? Should my fairly complicated SPA apps built with CRA be imported as components into a single SPA? I was just starting to figure out React, but now I have more questions than I did before.
1
u/maoMeow14 Jul 02 '20
My page has a drop down and a react table wrapped by my custom obj. I currently have the data reloading based on the drop down change but if I sort the table with 1 set of data when I change the dropdown I set the sort value to null in the wrapper but cannot get the sort in the react table to clear/restore. How can I clear the sort and load new data on dropdown change? When I made the sort value a prop for the react table I got "too many re-renders. When I refresh the page the sort clears, so how can I manually clear the table sort on the columns?
1
u/Deviso Jul 04 '20
Hi
What is the best way to catch errors from a api call using async await
const endpoint =
http://datasevice.accuweather.com/forecasts/v1/daily/5day/207931?apikey=mG0ISFW1ZGGHIV3rs5CSFQlF92CYSqhr&language=en&details=true&metric=true; const response = await fetch(endpoint); const result = await response.json(); this.setState(state => ({ forecasts: { ...state.forecasts, error: null, isLoaded:true, forecasts:result.DailyForecasts }, })); }1
u/wilecoyote42 Jul 06 '20
Hello. I am starting to learn React. I finished the Tic-Tac-Toe tutorial a few days ago and I'm working on my first project on my own. Silly question: can you write a function component if it has its own event handler?
In other words, suppose I have this component:
If I need to add to it an event handler function, can I just do this?
Or do I need to rewrite it as a class component?
1
u/toggalegend Jul 06 '20
This is quite a general beginner question about full stack development design.
I'm actually a server-side developer by training (Java) but in the last year or so I have been doing a lot of React for internal applications at my company. Most of these apps run on Spring Boot/MySql at the backend, bound together in port 8080 or similar. Then I'd run
create-react-appwith the front end at port 3000 probably, making API calls out to port 8080.The problem is when I do this, I always have to fix some sort of Nginx proxy and CORS configuration which just doesn't feel right to me for a full stack application. That's a lot of workaround for something as straightforward as an API call.
How do you guys get around this- what's actually best practice for a full stack application that's designed in this way?
1
u/alinserban92 Jul 07 '20 edited Jul 07 '20
why doesn't it work? I have this error :
Line 8:13: Unexpected template string expression no-template-curly-in-string
,
import foods from './foods';
import {choice, remove} from './hepers';
let fruit = choice(foods);
console.log('Here you go: ${fruit}');
let remaining = remove(foods,fruit);
console.log('i m sorry, we re all out, we have ${remaining.length}');
1
u/CauchyStressTensor Jul 07 '20
Okay so in my job I was introduced to a full stack (MERN) codebase and I became pretty good at solving bugs and introducing new features (this was hard) just by reading the existing code. It used hooks and reducers and no redux
Now I want to build a side-project in react and Idk where to start, I can copy the way my work project was built but I really wanna learn about react so what would be the best way to go about it
I have skimmed couple of tutorials which talks about different stuff, like redux, then using Classes etc
1
u/[deleted] Jul 09 '20
Worked on a ReactJS project that started in 2017 and completed in 2018. I'm getting ready to start on another, so I'm brushing up on the changes (new features, best practices, etc) since I last used it. The biggest changes seem to be Hooks and Contexts.
In my previous project, stateful components had class components; stateless could be function components.
A couple observations for reading up on this the past few days:
So....
A quote that leads me to believe this is the case:
1
u/babybananaa Jul 10 '20
Do anyone have recommendations on which tutorials to follow for building scalable app in react? There’s one on pluaralsight I was directed too but I rather not pay for one course, if there are some online or on YouTube. Thanks
1
u/Skrt_Vonnegut Jul 11 '20 edited Jul 11 '20
Hello, I'm attempting to use Material UI's AppBar component to style a Nav Bar. I'm trying to link the Hello button to localhost:3000/Expense_group but after referencing the documentation here https://material-ui.com/guides/composition/#button and copying it near identically, I still am not able to successfully change the path. However it is popping up in the bottom left hand corner of the screen in a pop up box, which is strange. Does anyone have a suggestion?
Here's a snippet of the code:
1
u/lems2 Jul 11 '20
I'm going through react tutorial videos and saw some js syntax I wasn't familiar with. How is it possible to have something like:
isn't anything in curly braces key value pair form? here's a screenshot of the webcast I saw it from: https://imgur.com/a/oCr1QRj
the video was going propTypes for react
1
u/kingducasse Jul 11 '20
I'm trying to get my form in check using radio buttons and state. I read many articles stating I'm looking for controlled components with state against using uncontrolled components with refs, except I can't seem to make the UI cooperate correctly. Each input value
checkedprop should register as null until state changes, except it all renders as false. Any ideas why? Code below.1
u/eyememine Jul 12 '20 edited Jul 12 '20
Hello everyone,
I built a few react apps but since I am terrible at design I decided to buy this theme for my portfolio site. However when I build it and send it to netlify or my site I run into this issue. Here is the example on Netlify. When I go to a different page such as "about" everything works fine, but if I refresh that page (or try to go directly to it) I get a 404 error example here.
I've really only built SPAs so I am not sure how to do the routing or uploading. This is all coming from the build folder. Also when I am running on localhost everything works fine, I can go to localhost:3000/about and refresh and there are no issues. Any help would be appreciated, thank you!
1
u/Dimasdanz Jul 12 '20
If you're developing a next js app, with graphql backend, do you still use redux for client-only global state like whether a cart is open or closed, or a global modal is visible or not?
1
u/badboyzpwns Jul 12 '20
Typescript + React question!
I have 2 components that share the same properties in props, like
Any ways to do this without repeating myself?
1
u/badboyzpwns Jul 13 '20
How do you add an element to an element using Refs in a functional component? Here's my attempt
1
u/fctc Jul 13 '20 edited Jul 13 '20
Hi, I'm trying to make a simple game using hooks. Every time I press a button it is multiplied. I assume my useEffect is the problem, but nothing I've added to the second argument seems to stop this behavior.
1
u/[deleted] Jul 13 '20
For my project I have to dynamically generate input fields based on information (such as name, id, type, label, etc) contained in a json config. For those who have a bit more experience, how would I go about doing this?
1
u/adam_wst Jul 14 '20
I’m building a React app to communicate with a stepper motor and I’m using useContext to store and share all variables and functions regarding the motor (such as position, speed, sendCommand, start, stop etc) and have one big context that basically wraps the app. All the variables are hook variables and they’re “shared” with children through useContext. When I rapidly update data (around 10times/second) about position, current,voltage the page displaying this data crashes. I’m beginning to think that useContext may not be optimal when rapidly updating variables. I’m trying to research optimization methods for useContext (such as useMemo, useCallback etc). Do you guys think it’s doable with useContext + optimization or should I go for something different like react redux. I’m happy to expand on the structure if I did not explain it clearly and I’m super grateful for all input!
1
u/zebhadra Jul 15 '20
I am trying to build a web app using React where a user can customize a shirt or a shoe, I don't have any idea where to begin for such requirements so I am looking for information about where to start regarding this kind of thing.
Thank you in advance for your time.
1
u/peck3277 Jul 15 '20 edited Jul 16 '20
I'm having problems with updating my state directly.
My state has a multidimensional array that represents a grid e.g.
This grid is set in my applications state with the useState hook.
I am passing grid to a custom class and manipulating it contents there. When I update the contents in the class it is updating my applications state directly without calling my setstate functionality.
I have attempted to use the spread operator and splice function on the array before passing to the custom class but this still does not work. Can someone point out what I'm doing wrong and explain to me why splice/spread operator isn't working as I think it should.
Example code:
EDIT:
I've gotten around my issue using this:
But I still thought the spread operator would work. Does the spread operator only do a shallow copy as opposed to the above method doing a deep copy? Any explanation would be welcome.
FINAL EDIT (EXPLANATION):
I've done a bit of research and I finally get it. I'm adding on here in case anyone in the future comes across this and is looking for an answer.
I understood that when I was passing my grid object to my new class I was passing it as a reference to the object. However the first thing I needed to do was get a better understanding of how JS passed objects. In JS there are two types, primitive types (bools, strings, numbers, null, undefined, symbols) and object types (arrays, objects, functions). When you pass a primitive type, the value is passed, when you pass an object a reference to the object location in memory is passed.
Very informative video on js value/reference
The next thing I needed to do was understand how to copy an object so that it is completely new object and not just a reference.
The spread operator, slice, assign etc methods do a shallow copy. They only copy the first layer.
So const newGrid = [...grid]; creates a new array called newGrid, however as it is filled with object types (arrays in this case) that are all references, when I updated each of these arrays I was updating the original arrays in my grid.
What I needed to do was a deep copy of grid. I achieved this with JSON.parse(JSON.stringify(grid)); however some say it is quite slow and that there are better methods. This stackoverflow post gives a very thorough overview along with several methods to perform deep copies
1
u/[deleted] Jul 15 '20
What is the best way to toggle the view of my app? I have it so that clicking the button changes the view to cards, but I want to be able to toggle back in forth. In my previous version, I used a class, and used and if/else function. I'm a little confused where I should put something like that in a functional component, and how to call it.
Thanks
const App = () => {const [view, setView] = useState("list");return (<div><button onClick={() => setView("cards")} >Change View</button></div>);}1
u/[deleted] Jul 16 '20
Setup question: anyone of the more seasoned users using doom emacs? If so, how did you configure it for react?
1
u/Abyx12 Jul 16 '20
Is there a thing like Bootstrap Studio for react? I know I can use bootstrap studio and then copy-paste the css/html but it's quite time expensive to convert then in multi-components ect ect
1
u/Deviso Jul 16 '20
I'm new to React and I'm wondering if this is the correct way to handle api requests.
I have an app components which is my parent component. All this does right now is renders out an issue component.
In my issue component, I do the api call to the Github API and save the data in state. Is this the correct way of doing it? Are there any improvments I can make to my code?
1
u/CYMAD Jul 16 '20
Hello, I get CORS error https://prnt.sc/tj7r72. my react app runs at 3000 port and backend(node,express) at 3002.I added proxy to package.json https://prnt.sc/tj7to2 but still get errors. I could not find any solution can someone please help me ?. It took my whole day to solve. I tried cros library in express It worked but then I was not able to get cookies between routes.
1
u/HiFlier42069 Jul 16 '20
React noob here, I'm trying to make a portfolio tracker SPA style website.
What's a good way to keep API request data in state so that multiple different pages can access it?
I'm fetching a list of assets and their current prices and working with that data on multiple different pages, but only want to fetch the data when the home page is loaded or refreshed.
All the pages are children of the App component and I'm using react router to assign each page to a URL path.
I thought to fetch the data in the App component and keep it in local state there, passing it down as props to the child components, but App unmounts before the API call resolves.
Is redux a good answer? As in fetch the price data from the home page and put it in the global store from there?
Feel like I'm missing something obvious..
Thanks in advance
1
u/badboyzpwns Jul 18 '20 edited Jul 18 '20
Typescript issue! Getting an error from key
1
u/Hanswolebro Jul 18 '20
Hey all, I’m pretty new to React, and I’m not sure I even know how to ask this question properly. I’m having a hard time wrapping my head around this.
Basically I’m creating an e-commerce site, and each product is a component. I am trying to create a modal that pops up that gives more details about the product. So far I’ve gotten the modal working but all the products pop up when you click the button instead of just the one that is in relation to the product that was clicked. Any ideas on how to set a specific component to have equal information to the component that was clicked?
I feel like this is probably an easy fix that I’m over looking but any help is appreciated
1
u/flabbydoo Jul 18 '20
No specific help needed but... anyone else prefer class components to functional? Im finding componentDidMount/ Update to be more straightforward than useEffect and its dependency list for rerendering correctly.
1
u/badboyzpwns Jul 18 '20
Should you use a functional component or class for React + Typescript? I like functional components because of Hooks, but I'm not sure if that's justifiable neough
1
u/phaiza86 Jul 18 '20
I have started reading Road to React and stuck on the difference betwwen
React Components, Elements, and Instances
if anyone can explain these in simple terms for beginner that would be great!
1
u/dkunal96 Jul 19 '20
I’m new to ReactJS. How can I practice to be a job ready guy? I’m a backend Java Developer and just wanted to dive in frontend side.
1
u/badboyzpwns Jul 19 '20
I think typescript is causing issues with history? my history.push("URL") always returns an empty component.
history.tsx
App.tsx
Header.tsx
1
u/SnooRevelations9512 Jul 19 '20
Hi all I have stumbled onto a problem which i am stuck on for days.. i am trying to build a full stack mern application. I had my authentication layer setup with passport local strategy, but upon login, req.user is getting undefined.. and user is still able to access the protected routes.. am i doing something wrong with the login logic? suspect that the user is not serialzied properly when login..
The below code block is working fine when I am using EJS as my view engine :(
pardon me if this is not the right forum to ask..
1
u/obliviga Jul 20 '20
I'm stuck on this problem: https://stackoverflow.com/questions/62987532/usestate-hooks-are-setting-state-correctly-but-console-logging-the-states-show
Hope it's alright to post SO links. Any help is most appreciated.
1
u/anthony00001 Jul 20 '20
I need advice if this is the right choice. I want to build an app that manages stocks ordrrs and purchase which means ill be using rdbms. Im looking into a solution that will let me easily select data from another table then associate that with my primary table so kind of like a form that pops up and lets me go through the records.
Example:
I create an order then fill out the necessary fields afterwards in the same page i want to select a product. I want to be able to search through my product by either a combination of name size price or dates purchased.
Is there a functionality in react that can easily do this?
1
u/johnlewisdesign Jul 21 '20 edited Jul 21 '20
Is there a sales (or ANY) prebuilt dashboard out there I can use to learn that will not ask me for a pro version, or send me on a 3 day dependencies dead-end when I realise it's Kendo, 2 years out of date version of node, using 2 versions of styled-components, deprecated in some way shape or form or simply fails its own tests?
So far, my experience in hitting the ground running with react is just basically a mess of broken dependencies every single app I try out and wasting my life going back to square one and binning off the repo. I'm an engineer type, I like to pick apart code.
All I want to do is learn from existing prebuilt code (alongside the tutorials I'm checking out already, please don't). Is it too much to ask that npm start just works first time on ANYTHING? I thought it was meant to be a timesaver. And I'm used to the command line.
It's actually making me want to put it down and walk away and I'm quite patient.
Trying to let go of PHP...trying being the operative word
1
u/iaskquestions12 Jul 21 '20
Can anyone tell me a good way to integrate React with WordPress? My current position is a WordPress role and I'm desperate to get out and move to a React role. I've been working with React for ~2 years now so I've got (I believe) experience for a lower level role however every job I've applied for and had an interview for the interviewer (or recruiter) loses interest in me when I say I don't have any professional projects with React, just personal projects. I've got a couple of full stack MERN projects and a few basic React projects so I feel like that should showcase that I do know what I'm doing, but again, everyone loses interest when they find out it's not professional work.
I'm aware I can use WordPress as a headless CMS and connect to React that way, but my understanding is that requires 2 domains (whether one is a subdomain or not) - one for WordPress and one for the actual React frontend. A majority of our clients take over editing their site once we finish building it for them, and the ones that don't are maintained by other people in the office, and I don't know if I'd be able to convince them of the benefits of something like that.
Is there any way to integrate React with WordPress other than that way? Or is there a way to kind of...hide the fact that it's being used headless? I.e., example.com is the React frontend and you can still access the backend from example.com/wp-admin ?
1
u/fctc Jul 21 '20
Hello React friends. I am trying to take a user input, leftArrow in the code sandbox below, and then change a value until it is done being pressed. Just like you would need in many game types. Have you seen this done with hooks? I've looked through a hundred programs and the only way I'm seeing people do this so far is with the && operator, which doesn't seem like it will work from my testing.
https://codesandbox.io/s/eager-dijkstra-g36rn?file=/src/App.js
This is one of my attempts, though it currently isn't even drawing the ship to the canvas for some reason. My useEffect has a zero effect dependency list. Is keyLeft just not being seen because of this?
I've seen this done with class based components, like Reacteroids, but if anyone knows of a repository that does this using hooks, or you could point me in the right direction I would really appreciate it.
1
u/badboyzpwns Jul 23 '20
Typescritp and React question!
FilmPreview.tsx
To implement <FIlmPreview> in a different file, I would have to look at the <FilmPreview> file each time and see if the props matches the interface. Is there a way to make it easier so that I don't have to look at the file each time? What I have:
Preview.tsx
1
u/[deleted] Jul 23 '20
Starting on React project for the first time since 2017 and catching up with the latest changes and conventions. Chief among those are the use of Hooks, Contexts, and function components that can now manage state thanks to Hooks.
At any rate, I just need to submit some data on a form to the API. The server will generate a PDF and send back to the client.
In the 2017 app I worked on, actions such as a PUT to the API were separated out into an ./actions directory. Is this still the convention, or is handling the async in the component itself the new norm?
1
u/cmaronchick Jul 23 '20
What's the best practice for using less files? I am using Ant Design (though honestly, it's giving so much trouble I'm thinking of switching to Material UI) and using the less implementation so I can create a theme, but I run into issues with babel umpiring the less files.
I have the project structured like this:
/src/component/componentName/componentName.js, componentName.less
I import the less file in the component, and I receive an error when I run babel on my src directory.
I thought that that was the best way to structure a project for readability, but if there is a better way, I don't have any issue with reorganizing.
TIA!
1
u/badboyzpwns Jul 24 '20
Typescirpt question!
From my understanding in functional components:
We are saying, "this variable will have React.FC methods/properties because it's a React.FC. "
But why don't we do:
This way we are saying that the component is also returning a JSX.Element.
For arrow functions,would my understanding be correct for:
we are saying, "this variable is a ()=> that returns a JSX.Element. And below would be invalid because..
This way we are saying that "the variable is a JSX.Element[] while infact it's a function!
1
u/nyamuk91 Jul 24 '20
Is it a good idea to use Context API to store localized strings?
1
u/Prithirajn Jul 24 '20
Is it necessary that ErrorBoundry components must alway be class components, or it can also be functional components?
1
u/Hanswolebro Jul 24 '20 edited Jul 25 '20
I’m having an issue dealing with loading data into state on page load and how it pertains to firebase
So basically I’m creating an e-commerce store to learn react and on page load a function runs that loads an object of products into state using componentDidMount, which I also load into firebase. The issue I’m running into is when I refresh the page, the changes I’ve made to items just refresh as well. Is there a better way to load these items initially into state. It seems I need to run the function sometime after I link to firebase but I don’t see where else I can run the function besides when it initially mounts. I hope this makes sense, I’m still fairly new to React
1
u/badboyzpwns Jul 26 '20 edited Jul 26 '20
Newbie Typescript and axios problem! The issue is listed in the comments. Wondering how to tackle it.
If it helps, here's my database; https://pixar-backend.vercel.app/films
1
u/MooMooMan69 Jul 26 '20
just wondering what best practice is here I'm building a simple react scheduler app as a coding challenge a jr dev job (i have not implemented context or redux atm)
Currently when I submit an appointment:
What is the best way to handle what i am doing?
Thanks
1
u/fpuen Jul 26 '20
Anyone know how to hide the content of an "index" page of a sub-router when a subroute link is clicked?
For example when
/porfolio/item1is clicked, the content of/portfolioshould be hidden.I tried to go up one level and add an exact match prop to the /portfolio
Routecomponent, but this did not change anything.My use case is below.
1
u/[deleted] Jul 27 '20
How would you name components that are based on premade components provided by other libraries? I am using Rechart to display some fetched data on charts and am using the BarChart component. I want to create my own component based on this component an am a bit lost with what is a good naming convention in such cases. I have considered:
Example of what I mean:
1
u/williamtheorange Jul 27 '20
My state array keeps resetting to empty. Here's my StackOverflow page: https://stackoverflow.com/questions/63094510/why-is-my-state-array-resetting-to-empty
1
u/musman Jul 27 '20
I'm moving from the Vue.js world and I have a question that is pretty subjective so please just answer with your opinions/experience:
I am moving to react because I can't find a good full-stack setup that works well for me when using Vue.js and I'm wondering if someone who has worked with React can give me some possible options they've used?
e.g. I've only used express to build the API for my vue.js app but felt like everything was way too custom built to scale at all.
1
u/Avihay Jul 28 '20
I am getting started at web dev! Have a decent background in coding using Python\C.
Currently using www.freecodecamp.org to learn JS.
I want to know if the route of JS -> HTML5\CSS -> React route would allow me to get into web development. I have 0 knowledge about what I should be doing to start a web app.
I want to write something in the lines of a to-do list \ bug tracker and make it work as a web app.
Are the tools (JS\HTML\CSS\REACT) will suffice? What more should I learn and if not, what is beyond these tools? Redux? (I couldn't figure out what it means really)
1
u/JudoboyWalex Jul 28 '20 edited Jul 28 '20
Right now, for some reason stockSymbol and data.pc get rendered first and displayed on the screen then avgCost get rendered and displyed later on the separate list. I don't know why they are not getting all rendered together at the same time and display on the same list. When I console.log stockSymbol and avgCost, at initial render they all logging the info then when I hit submit button, it renders all over the place. Please help!
}
1
u/Niesyto Jul 28 '20
How do I go about creating custom input for react-admin (which basically uses react final form) that's based on react-dnd. In react-dnd component I have and array of objects i can drag around to change their order in an array, how do I pass it to react-admin so that it gets sent to my data provider after the form is submitted
1
u/fpuen Jul 28 '20
I can navigate from my domain's /about view to /portfolio. and from /portfolio to /portfolio/item1. And pressing the back button works to go back to /portfolio.
but clicking the nav link to go to /portfolio from /portfolio/item1 (or any other sub-router view) doesn't work.
Can anyone see why? here is the /portfolio view below. I'm using React Router DOM 5.2.0
1
u/HanSupreme Jul 28 '20
Hey ReactJS! I’m pretty excited to learn this new framework. My background is Java & Spring, I’ve been meaning to get more into front end, I have a decent knowledge of HTML/ CSS AND JS.
React is still a bit confusing, as I have to keep typing in the npm create react at the terminal it looks like? Then I downloaded some other stuff via the terminal, like react cookie and reactstrap.
The docs are pretty good, I’m also looking to check into the FCC video on React and the programming with mosh video just to get started. Is there anything else I’m missing or should learn as a newbie?
Thanks in advance, and I’m excited to start lurking this sub 😂
1
u/[deleted] Jul 29 '20 edited Jul 29 '20
Hi,
I'm tying to stick a project on heroku, I have no problems running on localhost. The errors here are all taking place on heroku
I have an express backend set up with some of the below routes
And my frontend was created with CRA and react router. I need to cause a refresh of a page however when doing so it shows the error "not found" on the page alongside a 404 in the console.
I tried to overcome this by setting up the express route, to handle the specific url navigated to via react router:
However I get the same error. What's weird is that I can do a res.send("show up") here, to the same "dashboard" route, rather than sendFile, and it will show up in heroku. I can't feed the actual index.html page and relevant component to the url once refreshing the page.
Anyone have any suggestions?
Edited to say I can get round the issue with hashrouter as opposed to browserrouter... But would rather get browserrouter working
1
u/deaMorta Jul 29 '20
Hi,
i have a question about data flow in an application. i have a personal electron with reactjs project. and i feel disconcerted on whether the database or the state management get to update first or will they be updated at the same time. either way it's working for me but i question myself if im really doing the right thing. so is there any 'right way' for handling the data flow in an application?
1
u/badboyzpwns Jul 30 '20
Why is Cypress (end to end testing) not typically taught?
I can't seem to find any in udemy. It's mostly unit testing such as JEST and ENZYME
1
u/Deviso Jul 30 '20
Hi, I'm new to React and I have a question.
Do I need to learn a state management system like redux, or react context? At present I'm just setting state into the state object in my constructor.
1
u/Deviso Jul 30 '20
Hi,
I'm in my early stages of writing react, and I'm wondering does any know if there is anywhere I can send my small projects to and get code reviewed? (I'd even pay tbh)
1
u/[deleted] Jul 30 '20 edited Jul 31 '20
I'm doing a code review and came across something new. Someone on my team created a class to handle notifications.
Notifications.js:
In a React Component he then initializes it like this:
After that, inside the notifications class he does:
Like, it works but I've never seen anything like this. Feels like a massive anti pattern and a highly coupled class to MyComponent.
His notes refer to the Facade design pattern.
1
u/post_hazanko Aug 01 '20
Putting some kind of "global" render check eg. blank
useEffectconsole.log'ing 'render'I have been lucky catching dumb infinite renders, I realize usually you'll get one of those "infinite call stack" things and the app will stop executing code to stop memory leak. Sometimes some get through where it's not fast enough to trip that.
would get ugly trying to log every component
1
u/SelfManipulator Aug 02 '20 edited Aug 02 '20
Hello, I am a beginner and I have found a new tutorial to use from wesbos. Unfortunately, he didn't utilize destructuring and eslint is giving me a lot of "Must use destructuring state assignment". Does anyone know how I can turn this off? I have tried with this but it's not working:
"rules": {"react/destructuring-assignment": 0}1
u/[deleted] Jul 13 '20
Is the only benefit of using react hooks so that you don't need to write an entire class? Or are there performance benefits as well?
1
u/Nootuff Jul 31 '20
Hi I'm really new to react and I can't figure out how to actually install it or whatever it is I need to do to write code in it. I downloaded node.js and I have v12.18.3 installed as well as NPM 6.14.6 installed as well, but every time I try to type in the commands in the create-react-app installation method mentioned on many websites I get an error message saying: Uncaught SyntaxError: Invalid or unexpected token. Am I supposed to be typing directly into node? I have Visual code studio installed am I supposed to use that in some way? I see there’s a github repository create-react-app, does this mean I have to download it to my pc to run it? Does React just have a CDN I can use to skip all this?