r/reactjs • u/timmonsjg • Jul 02 '19
Beginner's Thread / Easy Questions (July 2019)
Previous two threads - June 2019 and May 2019.
Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch.
No question is too simple. 🤔
🆘 Want Help with your Code? 🆘
Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.
Have a question regarding code / repository organization?
It's most likely answered within this tweet.
New to React?
Check out the sub's sidebar!
🆓 Here are great, free resources! 🆓
- Create React App
- Read the official Getting Started page on the docs.
- /u/acemarke's suggested resources for learning React
- Kent Dodd's Egghead.io course
- Tyler McGinnis' 2018 Guide
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
Any ideas/suggestions to improve this thread - feel free to comment here!
Finally, an ongoing thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
4
u/MrDag0n Jul 10 '19 edited Jul 10 '19
I have a problem with a component which has an id prop passed to it.
If I goto /threads/[id] it will load the posts from firebase then they will disappear pretty much straight after. I think it has something to do with the method componentDidUpdate as it will render fine without it, however that stops me from being able to view other threads in the list.
Any thoughts? Thanks!
Edit: I'm an idiot, the parent component had this.props.match.params.id = ""
3
u/fortyNights Jul 24 '19
Is there an open source React project that is a good example of how to use Redux? I’m having some trouble figuring out what good Redux infrastructure looks like. Thanks in advance!
2
u/xilex Jul 07 '19
Hi, what are the advantages/disadvantages to using React directly on webpage ( https://maksimivanov.com/posts/how-to-install-react/ ) versus building it/creating a React app (like shown here: https://egghead.io/lessons/react-build-and-deploy-a-react-application)? I don't have enough background to understand which route I should take. In the past when working with jQuery I've just included the js library and worked directly on the HTML code. Thanks.
2
u/aedom-san Jul 09 '19
You know when you see PWA crash and it has a nice little image saying "Something borked, please reload" (Asana, Gdocs, YNAB, I'm looking at you) here's my loaded question; How do they do that? what kinds of JS errors can you and can't you gracefully handle?
2
u/w1nstar Jul 09 '19
I'm trying to learn HOC pattern. Certain components inside my app have to be aware of keyboard strokes, but not a single one has to do the same on a keyEvent. My guess is that there will be a HOC that gives a component this "keyboard awareness". I've done that, but I fail to see how will my component be able to listen to the keyevent, since I can't interact with the event outside the HOC, and it's the HOC who sets up the Listener:
What's the correct way to proceed here?
2
u/[deleted] Jul 12 '19
Can someone describe me differences between mounting and refreshing component? I know that after first initialisation component mounts and then after every change on state it recall render method. How about child components? If we recall render then child components unmount and mount again or what. Thanks in advice.
2
u/Bylee_ Jul 23 '19
I’m looking for some online classes to learn the full MERN stack.
Most of the ressources in the sidebar seems to be from 2018 or older and I’m a bit confused. I’d like something a bit more up to date.
Any recommendation ?
Thanks !
2
u/uriannrima Jul 29 '19
So, hello everyone.
I've already have some good experience with web development, and most of it with other frontend lib/frameworks (like Vue and AngularJS, not the Angular one) and I've got a job opportunity to work with React. I've already have some theorical experience with React (since, almost everything that I write with Vue, I tend to look how to do it "nicely" in React first), but never made something big with it (nor with functional programming and immutability). I've tried to make a small project to implement something with the things that I've heard from React (immutability, hooks, render props), to see if I can get myself more confortable with the library, using a simple codepen.
I would like to ask for some comments to my code. Tried to use everything that I know from the React/Javascript world, but won't lie, I've never worked with Functional Programming, nor Immutability to know if I'm doing it right or wrong, and probably there are bugs in the application.
The idea is pretty simple: Be able to calculate, but with dices. So anything that seems like a reasonable mathematical expression should work. Some edge cases are implemented to avoid some errors. You may click in dices multiple times to increase it's number of throws (1d4, 2d4, 3d4), and may use the wildcard dX to create weird dices (like a 1dX, constant 3, 1d3). Most of the code has JSDocs, and uses a stack to handle the formula. Hope it doesn't look too chaotic, since codepen allows a single file (unless a project).
Anyway, thanks in advance: https://codepen.io/uriannrima/full/VoeWjY
Any tips that I receive here I'll find some time to implement in it, so if something looks completely broken, I'm probably modifing something.
2
u/marmite22 Jul 31 '19
Hey,
I'm looking for a good tutorial or some code examples of a good pattern for requesting data from an API using useContext and useReducer? I'm starting a new project and the last time I used React was about 2 years ago and I've forgotten a lot and didn't have context and hooks when I last used it. (I vaguely remember redux middleware or something for handling this but it's been a long time and I'm no longer at the company so I can't access my old code)
Thanks.
1
u/Sunny-ROM-Rise Jul 02 '19
Hello, let's see if someone can help me with this doubt.
I have an object like:
const streams = { 1: 'Stream one', 2: 'Stream two', 3: 'Stream three' };Now, working with Redux, I create a deleteStream reducer, I'd like to return back an object which holds every stream but the one I want to delete, which I want to access using an id.
Let's say my action creator returns this:
const action = { payload: 2 };Now, in some other reducers (like the edit one) I used the spread operator to overwrite a given stream:
return { ...state, [action.payload.id]: action.payload };I want to approach the delete reducer in a similar way but I can't seem to get the syntax right, I want to do something like:
const { [action.payload], ...rest } = state;action.payload here === id (1, 2 or 3)
Then return the
restvariable.Any ideas?
1
u/loaded_comment Jul 02 '19
Hello, I am trying to figure out why and when the
npx create-react-appstarter template stopped using the es6 style for the App.js component e.g.class App extends Component {render(){...and started using the es5 style e.g.
function App() {return {...It makes it annoying to follow youtube tutorials and such. Why was it done? Is it possible to get it to generate the es6 style somehow? Thanks.
1
u/embar5 Jul 03 '19
Is this illegal?
My interpretation is this is inside a nested function and is illegal. And to make it legal the useEffect should be placed above the return. Is this correct?
1
u/dworker8 Jul 03 '19
Started learning react, I was following this blog post to make a nice TODO (surprise :) app with material design. The reason I liked this one was because it is using custom hooks. So I tcopied everything identical to the blog post and after that I started adding stuff to see how things work (react and the material ui, both are really new to me). Then I got stuck trying to show a snackbar using the material ui. The code is here . Once you open you'll see a green snackbar showing at the bottom. I'd like to show that AFTER inserting a todo :D
In your opinion, if I'm struggling with this, should I go back and study the basics? Or Is this a common thing to get stucked at while learning? Thanks for your time :D
1
u/hurrdurrderp42 Jul 08 '19
What is the good way to learn react after i got the basics down? I've made a couple of simple apps - todo list and weather forecast, and i'm kinda lost at this point.
What are some important concepts of React i should learn, and what can i build to familiarize myself with those concepts? I'd like to start with something easy so I don't get overwhelmed.
1
u/ladypalutena1231 Jul 09 '19 edited Jul 09 '19
I deployed my Create React App but I cannot figure out why my favicon is not showing. It shows fine on localhost but not when I SCP the build folder to my ec2. Website loads fine but no favicon.
Visiting my website/favicon.ico also works. I am launching the app with the command
serve -s build -l 80My index.html:
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />root@iZj6c2e6805nbwe3tquah0Z:~/build# pwd
/root/build
root@iZj6c2e6805nbwe3tquah0Z:~/build# ls -l
total 28
-rw-r--r-- 1 root root 756 Jul 9 12:49 asset-manifest.json
-rw-r--r-- 1 root root 3870 Jul 9 12:49 favicon.ico
-rw-r--r-- 1 root root 2140 Jul 9 12:49 index.html
-rw-r--r-- 1 root root 306 Jul 9 12:49 manifest.json
-rw-r--r-- 1 root root 540 Jul 9 12:49 precache-manifest.a72503c48ce12c5dfb1f4e91299ceefd.js
-rw-r--r-- 1 root root 1182 Jul 9 12:49 service-worker.js
drwxr-xr-x 4 root root 4096 Jul 9 12:49 static
Does anyone have any ideas?
1
u/badboyzpwns Jul 09 '19
I can't seem to find any source on cacheing in React. Could anyone briefly show me how to do it/an article on it? How do we browser cache a react project? What about CDN caches, is there a code we need to set up in our react project that allows us to use CDN caches?
1
u/cran Jul 11 '19
Is there a tried and true way to mix react and non-react/react-unfriendly code? I pull in a lot of code snippets here and there and the vast majority of it seems to be directly manipulating the DOM. I come from a bit of an AngularJS background and would usually just slap in some bindings where needed to get plain JS bits integrated. In React, I've been wrapping JS bits into React components via didComponentMount, but I don't really know how to integrate from there. Some libraries, like D3.js, seem particularly difficult to work with in a React-friendly way. Google turns up a number of approaches, but they all seem somewhat janky and lean towards re-writing a lot of code to fit React. I feel like this must be a common problem, but I'm not sure if there's a more accepted approach, or if people just bypass the problem and re-write everything to fit React. I would love to find a good way to mix the React and plain JS world with less effort.
1
u/piethonnoob Jul 15 '19
If Classes aren't hoisted, then how do components reference those declared after? In my sample code here: https://jsfiddle.net/nzmb1c9f/, how is ProductList returning a list of <Product/> when class Product is declared after?
Thanks
1
u/[deleted] Jul 15 '19
How do you add a ref to an element within a map() function if you don't know what data will be rendered from an API ahead of time? I know this isn't the 'React way' but is it acceptable to use document.querySelector() or document.getElementsByClassName() after the React component is finished rendering (ie. after ComponentDidMount())?
See following repo: https://github.com/christopheragnus/datatheo/blob/master/src/components/Table.js
1
u/rmoii Jul 15 '19
Hello ... I have two questions from the attached image .. My first question is how to delete the first line in a program format How do I transfer the status indicator from red to green when I press it with the mouse indicator? https://www.mediafire.com/file/4w99j230a3u945o/Screenshot_20190715_221733_com.Slack.jpg
1
u/workkkkkk Jul 15 '19
What's the difference between these two?
1
u/[deleted] Jul 18 '19
Could anything tel me the difference between
i've used both for the last few months, but I still don't know what the difference is exactly
1
u/[deleted] Jul 19 '19
Don't know if this is beginner, but would anyone know a simple way to add a "back" button into a component? I already have it built, and just need to toss one in to make it a little more user friendly.
1
u/[deleted] Jul 19 '19
I think I'm having a brainfart.
I have a JSON file of people. I want to iterate through and create a link for each entry/person, then when you click on the link, open a component that displays their info.
I have a Person component all done and in its own page. I know I've done this before, but I'm stuck on both the "iterating through the JSON to make links" part and (somehow) the actual routing of the link itself
1
u/chainsawtiger88 Jul 24 '19
Hi I’m a very new junior dev who was introduced to React and has been using it for 6 months. I was also introduced to react-strap along the way. I’ve been googling around for a concrete and succinct answer to this but no dice:
Can anyone explain to me what the benefit to using something like react-strap or even react bootstrap in a React SPA is over just using plain bootstrap itself? Is it just as simple as these UI frameworks don’t rely on dependencies like jQuery etc, or is there something else? Thanks
1
u/badass4102 Jul 24 '19
So I just started learning React...like an hour ago. I've been following this tutorial but I'm getting this error. It seems the syntax in the video is a little different than what's default in my App.js file. instead of calling a class, it's function.
Here's my code and error Any help will do thanks.
1
u/10jy Jul 25 '19
Hi, learning webdev and react for a few hours...
https://codesandbox.io/s/8lpo68lp28
Came across this, really liked it so I'm now building a site with scroll and anchors. (long scroll spa)
My question is how do you put content on each of the pages? Instead of the texts that say 'Scroll down' I would like to populate it with buttons, pictures etc
Also how do you implement a side scroll like in this? https://codesandbox.io/s/m34yq5q0qx I'd like to populate each slide with pictures and text and let users scroll between them
1
u/po35 Jul 25 '19
How can I access a class component's state from within a render function? I get
TypeError: Cannot read property 'state' of undefined, check this Formik Multistep example, line 109 where I try to access the state:https://codesandbox.io/s/winter-cache-gk5xe?fontsize=14
1
u/djingrain Jul 29 '19
My
npm installfails when trying to install node-sass. Here is the error:Any ideas what I should try?
1
u/NickEmpetvee Jul 30 '19
Would anyone have a tutorial link on how to get success or failure messages to show in a React form? The form would post to an end point and based on success or failure, display a success or failure message in the dialog. I have an idea about how to do it but if there's a quick good tutorial would appreciate sharing.
Note - do not need form validation help. This is just for success and failure from API.
1
u/OddHeadSpace Jul 31 '19
I'm really struggling to wrap my head around re-usable data in React. I have an API call that returns a JSON which I'm then converting into an array and storing in the component's state:
What I want to do is to call this API once, store the data in a variable which I can re-use on several pages. I'm using router for the pages, most of which will use the data, I just don't want to re-call the API for every page. Any help appreciated!
1
u/ntlrd Jul 31 '19
Hello, i'm a newbie react dev.
Question, how to stop re-rendering all
itemspassed in a component as an array.example:
i want to only re-render a specific
Item, the item that was changed.Good day!
3
u/[deleted] Jul 20 '19
I'm trying to find all the React components in React Dev Tools. I'm doing this by searching with the search bar with the regex /^[A-Z]/ as React components start with a capital letter and the angle brackets are not needed.
However, React Dev Tools doesn't seem to recognise upper/lowercase. /^[A-Z] gives me the same results as /^[a-z]/. Can someone please help me with this issue?
3
u/[deleted] Jul 23 '19
So i have a state array of approximately 2500 items, specifically cryptocurrencies, and I would like to not only filter/map results of the users search input, but to also have items I deem to be 'more important' to present at the top of the returned list of items.
E.G. Bitcoin has many, many copycat cryptos that aren't really worth thinking about. I don't mind having them there so much, but would prefer it if they didn't show above the actual bitcoin, maybe followed by 2 or 3 that aren't completely irrelevant
I havent tried all that much, as my research has been quite fruitless. But so far my thoughs have been to add properties into the 'important' array items and maybe have a check on if they have this property (true/false), if so display them first. But honestly, I don't even know the best way of going about that.
here is an example of my array that's being filtered:
here is the method im employing to enable filtering:
So does anyone have any advice to give weighting to specific listings? at this point even some resources to aid me in removing 'some' of the lesser known copycat coins...
1
u/po35 Jul 26 '19 edited Jul 26 '19
Trying to grok the meaning of the pattern
static Page = ({ children }) => childrenin Formik's multistep example.It's a static method of the class
Wizardand can be called without instantiation of Wizard. When it's called, it takes the children of the, with<Wizard.Page />, instantiated JSX component as argument and returns them back to the constPage. I assume some sub components are create in the namespace of Wizard but then I can't follow anymore. What is the underlying intention for this design/pattern... so what is going on here?2
u/Symphonia1X Jul 04 '19
Hi guys, i'm trying to structure the folders of my App but i'm super confused.
What's the best way to organize your React app using hooks with local states? (not using Redux atm)
Also is it easy to switch to Redux later on?
Since i don't have enough experience, i don't know if i will ever need Redux in the future. When i search online, there are many opinions on Redux being so hard to learn and unnecessary for some apps.
In my app, there are many api calls and i started to get confused. Am i supposed to handle these calls in each related component's useEffect() hook? (componentDidMount for the class components)
Am i supposed to use localStorage/ sessionStorage for each component that i want to cache the state?
These tasks feel so fundamental and it feels wrong trying to apply them for each individual component.
And lastly, what is serviceWorker.js used for which comes with create-react-app? Is it related to any of the tasks i mentioned above?
Thanks...
2
u/TheRealKeanuGrieves Jul 06 '19
I'm using React, Firebase and easy-peasy.
Here's the quandary: I have to fetch data from two sources (one from Firebase, one from an API that replies in XML) and then merge them, a process that has to happen on the initial load of my landing page. When I store these quite lengthy JSON arrays in the Redux store, I get a warning that Redux is trying to handle too much information. I've been thinking about running the process in the component only, and then passing the resulting merged array back to the global state. Do you think that would help? Or would I benefit from migrating the whole thing to Next so it could use the server instead of the client's browser?
Bonus, completely optional question: would migrating to Next reduce the number of read/writes I perform on my Cloud Firestore? Are there any other hiccups I should be aware of?
I'm relatively new to all of this, and my deadline for completing this project is approaching rapidly. I'm sweatin' here.
Thanks!
2
u/ladypalutena1231 Jul 07 '19
Hi newbie here. I have a hypothetical wondering if someone could help me with.
Let's say my React webpage has 100 input fields. Imagine I input some text in all of these input fields and at the bottom of the screen I can click submit. I want to know what the idiomatic React way to get the text values of all of these input fields. Does anyone have any suggestions? Thank you
2
u/Oipotty Jul 08 '19
Hello - I am working on a personal project where I plan to use react-viz to create an interactive dashboard. Currently, I able to load the data in from a CSV and output it as a static graph. What I want to do is to give the dashboard some functionality, for example a date-picker. What is the best approach to implement this?
My thoughts: have a datepicker with a event callback that changes either State (or a Redux Store) variable to the selected date. This is where I'm not too sure about; where in my React app would I filter the data set? Would I, in the event handler function from the date picker, update not just a date variable in state but also filter my data (which would also be stored in state) and then have my graph point to the data in state? Just looking for the best approach.
2
u/Oipotty Jul 10 '19
I have currently set up a dashboard in react using mock data read into and saved into a redux store. I am using selectors to filter that data based on user interaction. Thinking ahead to when I want to get that data from a rest endpoint, where would I put that rest API call? From what I've read, the best place to put it is in componentDidMount and then dispatch an action to update the data in the store. Thoughts?
2
u/CafeRoaster Jul 16 '19
I'm looking to use or create a component that consists of a form
inputand aselect. The user should be able to create new options for theselect, which is also stored in a database object. Next time they go to use the form, they should see this new option, or they can create another new one.I apologize if this is difficult to understand. I'm a super-newb, so I may not be using terminology that would more succinctly explain my use case.
2
u/fransquaoi Jul 17 '19
While you're working, how do you like to quickly run your code so you can see how badly you're fucking up?
2
u/rayzon2 Jul 17 '19
Is it preferable to use functional or class Components? Ive been using functional components and hooks in all my projects because it makes more sense to me than using classes, and it feels less verbose. Is this more of a preference thing? Or is there a major difference in using one over the other?
2
u/[deleted] Jul 18 '19
Ok, this may be a little tricky to explain, but I'll try my best.
What is the best way of binding data from a form submission to an existing state array?
I have a state array that i would like to access and push another property into, but it must do this contextually, based on the form in which the data was submitted into. (ie if it data was submitted into the form generated from the mapped item of the array, then it would be added as a property to it's own array)
Forgive the explanation, but finding it really hard to put into words - i hope the code further down will help.
I have tried to use the key of the individually returned item to setState in the correct 'item' of the array and a few other things, but not been very fruitful at all.
here is my state - See 'pairs' below. it is an array, with 3 arrays inside it, each of which has 3 properties. I would like to add a 4th property to each of these, contextually depending the form I submit
here is the rendered section of this array, it spits out each item in the state.pairs, along with a form.
My intention is to be able to type a number into the form and have that added to the state.pairs[insert corresponding array here].
eventually I would like to use some equations on the 3rd and 4th items in the array and spit out a figure.
but as it stands i simply cannot find a means to add a corresponding property to the correct items in the state.pairs array
Pastebin here if you feel you need extra understanding of my issues - https://pastebin.com/KnWGAVhg
2
u/chrisan20 Jul 24 '19
What is a good guide/course/tutorial for something that is Typescript + Redux + Router
I've only had luck finding things individually and would like to see something combine all 3
2
u/[deleted] Jul 24 '19
Is it possible to make "full stack" web sites using just react and some database like mongo or firebase? I just start working as a freelance front-end dev, and I am looking to study something to make big and "complete" projects. My first thought was learning node to make some crud apps or something, but I would like to learn react AND make projects like cruds etc (because there are a lot opportunity for 'crud apps' for small companys here)
2
u/liohsif_nomlas Jul 30 '19 edited Jul 30 '19
Hi, I was wondering if a guest user and a user with an account and has logged in, both have access to the same homepage, where the difference is the logged in user had access to a few extra features how should I handle the routing to this homepage?
I found on stackoverflow that when you want to protect a route from unauthorized users, you should be creating a private route and within that use <redirect .../>. The thing that is confusing me is technically the homepage component can be accessed by a guest user as well and it seems using a private route for this page is unnecessary? I am thinking that I should use a role-based access control(RBAC) where depending on the user role being redirected to the homepage, different components could be rendered.
I guess my question is should I be using private routes for a page that can be accessed by guest users and registered users? Any advice would be appreciated.
1
u/HeinrichHein Jul 03 '19
How/can I store .env variables while using create-react-app. From the docs, it seems like I can't actually hide the .env variables. They will show up regardless when inspecting the app with devtools?
I would only be storing the url endpoint for my Node backend, that's going to be hit with my ajax requests. Is there any point to storing the url endpoint in the .env then? As opposed just storing the url endpoint as a string in a config.js file?
1
u/ReyesEvan Jul 03 '19
Good night, all. I'm not sure if my question is as dumb as I think, but I've been struggling with a quite straight-forward problem for all day long.
See, I'm programming a sort of "chat bot" with React (my first application, actually). Right now, I decided to model the dialogs the bot can say and the options the user can click with a directed graph where every vertex is a message from the bot or an option for the user to choose.
Then, for now, I have this Chat component where the first "dialog" (the first set of messages and options) is going to be extracted from the graph and then every message/option is going to be rendered, it works well so far, but what I'm struggling with, is that I don't want all the messages to be rendered simultaneously, but one at a time (like in an actual chat) and I cannot manage to accomplish that. I've tried some solutions, but I cannot do it.
What I'm trying right now is to store in the
stateof Chat an array with the messages that should be rendered at that time, it is initialized empty, then incomponentWillMount()is called a function that will add one message at a time every second with asetTimeout()(my idea is that every time the state is updated then it should be re-rendered with the new message, but maybe I'm wrong) and there is the problem, the timeout never delays the call of the function, it still happens instantly.This is the function with the timeout:
currentDialogis an array ofGraphVertex, each contains a message/option andupdateCurrentlyRendering(message)updates the state of the component pushing message to the state's array I mentioned earlier.The full code is here. The only important stuff is in
index.jsin case further reference is required.Thanks a lot for any help, React is being quite confusing for me right now and any help is welcomed. If I'm doing anything the wrong way, please point it out too, please.
Good night and thanks again.
1
u/workkkkkk Jul 03 '19
How to handle async actions with useReducer and useContext? Here's what I'm currently doing but wondering if there's a better way. Essentially I don't love calling the action and hook separately.
logout() is essentially an action creator, it does an async request and returns an action of type LOGOUT. And here is my provider.
Any thoughts on a better set up?
1
u/akalantari Jul 03 '19 edited Jul 03 '19
Hi,
I'm having a strange issue with UseState. If you have a look at my deployed version here. (Please click on the left hand icon when the page shows you "are you lost", seems to be some issue with the router and github pages!)
You see the number next to "Dashboard" is coming from here.
const [state, setstate] = React.useState(0);React.useEffect(() => { setstate(state + 1); }, []);And if you look at when opening and closing the sidebar or basically any rerender of the dashboard component you will see the value goes back to 0 and then gets increased to 1. My understanding from usestate is that it will persist the state value however here it seems to be reseting it everytime!
Can anyone help please? The whole repository is available here
1
u/CharlieWebDev Jul 03 '19
Could someone possibly show me via screen sharing how to connect a node js backend with a react native front end? I have them running concurrently, it connects to the cloud atlas mongodb cluster and tells me its connected and I run the app on expo but that's about it so far. I have mongoose, express, other things installed and even have a schema and models but need some help because I keep getting lost in youtube videos / docs. It;d be greatly appreciated and if you need money for your help and it all works out we can figure something out
1
u/kevinfaguiar Jul 04 '19 edited Jul 04 '19
Let's say I've coded two layouts: one for all common pages and one for all documentation pages.
My current approach is creating two Higher Order Components: common layout HOC and documentation layout hoc.
When I say layout I mean a structure like this one (header, sidebar, footer, content, etc, I mean, a common layout that will be shared by multiple pages): https://ant.design/components/layout/
What is the best aproach in this scenario? I'm thinking in using a Higher Order Component and put something like this in my App.jsx:
1
u/HeinrichHein Jul 04 '19
Using react and redux, what is the best way to implement a day/night mode? I'm also using SASS. So this might get a little messy...
But my thought was to have a button/switch that flips a boolean in the redux store. Then in the highest app component, have two objects, containing the day/night styles. Depending on the redux store's state, pass the correct style to the components affected by the day/night styles?
1
u/burton6666 Jul 05 '19
I just started learning react but got some problems. I am trying to get the method
handleMaxVoteto return a string with a line break in the middle. But that string then is sent toreturn(<p>{text}</p>)and I can't figure out how to change my code to solve this problem. The only thing I have tried that seams to work is to havehandleMaxVoteto return an array where I insert a<br />in the middle. It look ok but in the developer console I get an error "VM7053:37 Warning: Each child in a list should have a unique "key" prop." How can I solve this problem?import React, { useState } from 'react'import ReactDOM from 'react-dom'const Display = ({text}) => {return(<p>{text}</p>)}const handleVote = (selected, vote, setVote) => {const tempArray = [...vote]tempArray[selected]++setVote(tempArray)}const handleMaxVote = (anecdotes, vote) => {const maxValue = Math.max(...vote)const maxValueIndex = vote.indexOf(maxValue)const maxVotedAnecdote = anecdotes[maxValueIndex]return maxVotedAnecdote +"\nhas " + maxValue + votes}const App = (props) => {const [selected, setSelected] = useState(Random())const [vote, setVote] = useState(new Array(6).fill(0))return (<div><Display text={handleMaxVote(anecdotes, vote)} /></div>)}const anecdotes = [...lots of strings...]ReactDOM.render(<App anecdotes={anecdotes} />,document.getElementById('root'))1
u/duhtruon Jul 05 '19
I'm reading the Hooks React.js documentation and it mentions 'Setting up a subscription to a data source' or 'subscribing to data'.
What is a subscription/ what is subscribing to a data source? Not sure if its a special term in React or not. Thanks!
1
u/[deleted] Jul 05 '19
Does anyone have an idea what the performance cost of using styled components is, and at what point it is noticeable?
1
u/mynonohole Jul 05 '19
https://codesandbox.io/s/quirky-sunset-rhept
I am doing Grider's React tutorial and I want to test this useEffect hook doing async functionality. Does anyone have any examples testing useEffect hooks with Jest/Enzyme? I know I need to mock the axios call and possibly use mount() to allow the hook to function. Thanks in advance.
1
u/realchriswells Jul 06 '19
Hi everyone,
I've been doing frontend development for about 15 years, with some backend thrown in for a chunk of that but in the last 5-6 years solely frontend.
In the last year or so I've been looking at React and just started seriously using it in the last few weeks. I understand the concepts and theory of props and state, but when it comes to actually doing it off my own back I seem to struggle actually figuring out the syntax and logic, specifically when it comes to passing props and state around between components.
I'm just wondering if there is an easy way to figure this out and make it click?
1
u/jmacklin1 Jul 06 '19
Hi all silly question, I’ve been learning react via video tutorial. Every time I start working on a project it states that my syntax is incorrect(fine), I fix it and another error shows and this cycle continues. Am I just not doing something right or could it be something else ? Could it be my code developer isn’t up to date or I forgot to download something. I’m at a lost
1
u/TheFirstMeiFunny Jul 07 '19
So I’m trying to make a website with a header using react bootstrap and a custom sticky footer using absolute positioning. What I need is transitions between one page to the other. I have used CSSAnimation and TransitionGroup to achieve this. But the problem is the smooth animation requires absolute positioning. So when the page content is large, it overlaps with the footer. Is there a way to achieve page transitions without absolute positioning? The footer has to be sticky. I am using React router to route between pages.
Right now, I am detecting the page size and checking when the overlap occurs and giving a value to top of footer. But I am not happy with this solution.
1
u/argiebrah Jul 07 '19
Hi, I created a repo from a Codesandbox code snippet and I want to keep it working it locally. I just found the dependencies and node_modules files are not created from the codesandbox onto github. Should I go on and install the create-react-app and dependancies or is there a better way to approach this?
1
u/Poopingcode Jul 08 '19
Anyone know how you could have a bunch of number valueboxes (like 15+) and the parent to keep track of all of the values as they are changing?
1
u/reller_eu Jul 10 '19 edited Jul 11 '19
Not sure if I need to make a post for this.
I'm using the library react-vis to make a chart like this one. I have a hard time getting the styling right. The documentation is pretty well written, but I can't seem to get out of what I need.
I have a hard time getting the answer above the horizontal barchart and enought space on the right for the % to be shown. When trying to google for other example or solutions for my problem I get redirected to the docs.
I have spend a lot of time trying to get it right and feel like using something else instead, but that feels like a waste of time and I do think the library is a good one.
Maybe one of you have had some more succes than I have had and it would be awesome to get some solutions of guidens.
1
u/eyememine Jul 11 '19
How do I make a list items from 2 different array? For instance
Const array1 = [ "one"
"two"
"three"
]
Const array2=[
"1"
"2"
"3"
]
I want the list to look like
•one 1
• two 2
•three 3
Merging them makes the array 6 items. I feel this shouldn't be this hard but it's got me stumped. Thanks for reading!
1
u/isengart Jul 12 '19
Hello I'm struggling to implement the translation functionality using react-i18n. I have a detailed post with what Im trying to do and what I tried so far in StackOverflow. I would really appreciate if someone could enlight me as Im searching for this for more than 4 days -.- SO Question
1
u/kudaros Jul 12 '19
I'm more of a scientific computing person trying to get better at modern front-end development to scratch the itch (and be less reliant on pre-made things for side projects). I'm at the point where I can make some basic interactivity and integrate a back-end (more my speed), but I don't CSS so well. For integrating CSS, I think I like the idea of CSS-in-JS approach.
The three gatsby starters I've taken a look at use emotion but it seems people prefer styled components. Is styled components still the preferred way? One key point I see is the allow users to ' fall down the pit of success' paradigm which I like. Not sure if things have changed substantially since the discussion here -- https://www.reddit.com/r/reactjs/comments/9d583z/announcing_styledcomponents_v4_better_faster/e5fgu0f/
Thoughts?
1
u/hurrdurrderp42 Jul 13 '19
How do i write this better?
componentDidMount() {if(localStorage.getItem("notes")===null){}else{this.setState({notesText: JSON.parse(localStorage.getItem("notes"))});}}It wouldn't let me use !=== , i need to set state from localstorage only if it isn't empty
1
u/furchtundzittern Jul 14 '19
Can someone review this devise_token_auth React/Rails setup?
https://github.com/cody-the-coder-commits/react-rails-restaurant
I'm new to react so I'm not sure if the Redux/HTTP calls could be done in a better way, would you recommend using https://github.com/kylecorbelli/redux-token-auth instead?
1
u/BSeipler Jul 14 '19
Newbie here. What is the best way to work on the same React app between two computers? For example, between a Desktop computer I work on when I am home and a laptop that I like to work on when I'm not home. Should I use Dropbox for the files? or is there a standard different way of sharing the files between the two?
Thanks!
1
u/coolyoga Jul 14 '19
On the webpage I am building, I am using Typed from react-typed. I have two different lines of text that I want to render one after the other, but instead they are rendering at the same time. Is there a way I can fix this or should I used something other than react-typed.
This is my code for that section
1
u/php_developr Jul 14 '19 edited Jul 14 '19
I saw on a youtube video someone using .reset() to blank out all form fields. But he wasn't working with controlled inputs. Do you guys use .reset() when you want to blank out all form fields, or should one set every field back to '' (empty string) using setState/the state setting function, when working with controlled inputs?
1
u/[deleted] Jul 14 '19
How to render a react component on an interval with socket.io?
1
u/Competitive_Mango Jul 15 '19
Hi guys! I am a sysadmin and i want to make tools for my colleagues. I am decent in scripting in powershell, but my javascript knowledge is not so great. I'm trying to make an electron-app with React which is supposed to call a powershell-script(The module im using is Node-powershell). I manage to get this to work if im just using electron, but when i try to implement it with React, several errors pop up:
The code im trying to implement is this:
My theory is that this does not work because websites are not allowed to start progams on your local computer. If this is correct, is it possible to pass the command to NodeJs somehow?
1
u/HeinrichHein Jul 16 '19
How do I control the value of a CSS property as state changes? I am also using SASS and redux if that matters.
For example: If I have a button that increments a property of state by +1. Every time the state increments by +1, I would like the
border-widthof the button to increase by 1px, thus increasing the border of the button, obviously.I think I can do this just by writing inline styles. But I was wondering if there was a way to pass the current value of the state directly to the SASS stylesheet or similar?
1
u/incept_shawn Jul 16 '19
In a web app of mine, I've used the Shards React library for some components. I wanted to change the default colors of these components in my app. However, when I tried with CSS, the changes weren't getting reflected in the app when I viewed in on the local development server. However, after deploying my code to Netlify, all the changes got reflected. Is this normal? Any reasons for this?
1
u/php_developr Jul 16 '19 edited Jul 16 '19
This is set as both a Link to and Route path but clicking that link doesn't match it to the route
it will work with only this format: /a/b/c.php
but the moment I hardcode the query params starting with
?it breaks. A problem because my framework needs that first param (2nd is mine for this routing task).How would you guys alter this to work?
1
u/filemon4 Jul 17 '19
How to implement http/2 in create-react-app application?
1
u/workkkkkk Jul 17 '19
I have a snackbar like component where basically i pass in buttons and render them as children either being on the left or right of the snackbar. Currently this is what I have
This works perfectly fine but imo is kinda ugly. How I would like to use it would be more like this
However, I'm not sure how to conditionally render children like this without doing quite a bit of logic in SnackBar, which kills its simplicity. It seems kinda silly to me to have to loop through the children array looking for the prop of each element twice and then to also cover the case of only passing a single child where props.children will no longer be an array (i think). Is there a simpler way to achieve this?
1
u/[deleted] Jul 18 '19
can someone help me map over an array of objects that has their own objects inside of it?
I am receiving data from an API containing cryptocurrency market data. When a user searches for a crypto the information of that crpyto is fetched and added to state. I would like to have each item that is returned from the API render to the user, slowly making a list of the data and subdata.
I'm aware of mapping on an array, but cannot seem to get objects mapped (having attempted 'Object.key.map' too)
I have tried to target the items in the object, rather then the full objects returned themselves, but React doesn't seem to like me using uppercase in my code, with the dot notation of getting items from an objects (uppercase appears to be required by the API as it returns data with uppercase:
the pertinent section of my code is
I'm aiming to extract and render the cryptocurrency name that is returned (should match user query), as well as the price (in USD) that is returned with it.
ideally along the lines of
Selection 1: BTC, $9452 at time of query.
1
u/Sleek_Devigner Jul 19 '19 edited Jul 19 '19
REACT SERVER SIDE RENDERING REDIRECT ISSUE
Hello Everyone! Please I need help concerning redirects in SSR.
Authentication is successful and Everything works fine until the page redirects to the
/user. I need to make my server know about the redirect so I can render the page at the server and also to enable the server send the required data to the client. I tried using the context API (context.url) according to the react-router docs but my server isn't detecting the redirect. Everything works fine if I refresh from the browser tab but on auto redirect from login page, it crashes because the/userpage couldn't get the required data from the server.Please I would love to get a solution to this issue or anyone's thoughts on how I should go about this. I am also open for further discussions and clarifications concerning my code. Thanks a lot.
Below is my Login.js
Below is my server.js
And here is my Route
1
u/petar95 Jul 19 '19
Hey guys, I am working on a uni project and I am responsible for the group chat feature. So I already googled for components and found: https://github.com/Wolox/react-chat-widget. I like the look of the component, but it's build for a 2-people-communication. The renderCustomComponent method helps but unfortunately the handleNewUserMessage method is required which automatically renders a message, so in this case renderCustomComponent() doesn't help much. There is a pull request which solves that issue: https://github.com/Wolox/react-chat-widget/pull/98 but I wasn't able to install it correctly with npm. When I install it the folder doesn't contain a lib directory etc, I have pretty much the same issue as shown here: https://github.com/tleunen/react-mdl/issues/20 . Has anyone a idea how I could still solve this?
If not:
I wanted to ask how I could achieve a similar look? How is this "popup" called? Overlay? I have only 2 days left and if I am not able to install the PR in the next hours I'll just build my own component.
TIA
1
u/duerdod Jul 20 '19 edited Jul 20 '19
Not sure if this is the right forum to ask, but anyway, here goes. I’m having some trouble wrapping my head around my development process.
I have my client side boilerplate from CRA, and then I have my server running Express with GraphQL-yoga.
While in development I’d like to run both the Webpack devserver from CRA and the Express server, but somehow proxy all my request (not just API request, I think?) from Webpack to Express allowing me to build some sort of authentication based on clients headers. Is this even reasonable?
Running both servers aren’t a requirement of course. As for now I’m running Webpack server side which creates a bundle of my frontend dev build and serves it on a single devserver. I think this is fine, but it’a feels kinda unstable and sloppy.
I know how to serve a static production bundle from Express, but that process is time consuming because I need to create a fresh bundle. Using the proxy in CRA haven’t got me any further, since I’m only able to proxying “API requests” or everything, neither from package.json nor the manual proxying.
I have a feeling that CRA is bottlenecking me. Should I step away from CRA? My goal is to be able to develop small full stack applications with main focus on front end. Is there even such a thing?
TD;LR how does the general process look like while developing a full stack application? Should I focus on the UI first, and then handle it server side? Am I completely missing the target in some manner?
Would love to have someone share some thoughts on this, but I know it’s time consuming for y’all. Maybe someone in the same situation? I’ve been googling for days. I’m all out of keywords now. :)
1
u/[deleted] Jul 21 '19
If I want to build an education app for Android, iOS and the web, should I learn JS/React or build natively?
1
u/giediprimes Jul 21 '19
Hi, I am working on a Next.js + Express server simple registration/login system so here is the chunk of code I have problem with:
So I have problem with last if/else statement because if there are some errors I want to re-render this register page and pass that errors array with errors to that Next.js /register page but I got that 405 error method not allowed and in server console i got UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client error and I can't find anything on the internet about how to pass errors object/array from server to Next.js page.
1
u/TheFirstMeiFunny Jul 22 '19
So we can add svg images by using Src attribute of Img tag in simple html right? Why can’t the same be done in react? When I do so, the src is replaced by the xml code of the svg file in the output. Is there something I’m missing?
1
u/[deleted] Jul 23 '19
New to react, loving it... the only thing I'm struggling with is how to store complex data in state, and effectively retrieve it.
Talking mainly about nested objects inside objects, objects nested in arrays, arrays in objects etc.
I'm really struggling to find a consistent way to tackle this, anyone got some good resources for understanding the best practices of managing nested api data adding/removing/manipulating?
1
u/MCPO_John117 Jul 24 '19
Hello, I have gotten into React webdev in the past month. I am currently using create-react-app to make projects. My PC has 4GB RAM. The issue is that whenever I run the page using
npm startmy PC starts slowing down and eventually hangs. I tried usingnpm run buildbut the error messages don't make sense that way. Is there some way to make the app use less system resources in production, like some settings I can disable to make it faster.1
u/Pandarocks123 Jul 25 '19
Hello all, Working on a project and I am having a hard time trying to figure out how to test a typescript function inside a functional component. For example if I have a fetch inside a useeffect hook, how do I mock that fetch function in jest? I asked this question in stackoverflow https://stackoverflow.com/questions/57154476/how-do-i-mock-a-function-within-a-functional-component-in-typescript. Didn’t get any insight, so any of you got some tips for this?
1
u/9_skynine Jul 26 '19
beginner question:
so i was looking at redux-form where the `Fields` could be sent `values` where you could send the current values of the fields.
if we have 2 field values being sent. how does that work. i know the name is what the `Field` component would use to know which field input to use within it. But since for Fields we have more than 1 field and there for more than 1 name how does this work? is it the first value corresponds to the first name field and so on.
am i wrong about the name for inputs thing?
https://redux-form.com/7.4.2/docs/api/fields.md/#props
1
u/[deleted] Jul 26 '19
Hi, quick question coming through:
I am making an app that allows you to revert any changes made to text fields. In order to achieve that, I have a function in onBlur: it's meant to save the newly entered values, which later get rendered in a box that you can click on to revert the changes. The problem is, the function gets called onBlur, so this only returns one value (the one I just changed), but I want to show the whole form/all input fields to the user. How can I make it so that if a field has nothing in it, instead of passing nothing, the value from previous state gets passed?
So far, the function is sth like this:
And is called like this
<TextField onBlur={props.handleSubmit} />1
u/crespo_modesto Jul 27 '19 edited Jul 27 '19
What is an alternative to re-rendering rows, just to inject some extra UI/piece of node. I could use a ref/replace the dom node with a new node/code is that a thing? Without losing event bindings.
See this simple interface here where I add rows, want to edit it. Initially my design would have had the selected row grow/show some extra buttons on top. But those would not be rendered/hidden on load. It would be "injected" but that's the thing. I can dynamically render that by re-rendering from setting state.
When should you be worried/concerned about re-rendering(as long as there are no processes just repainting). In this particular case I don't think I would have more than say 10-20 rows at a time.
1
u/ProbablyGoku Jul 27 '19
I'm on a team building a custom component library, and we're trying to decide on a ui toolkit and related technologies. Price is very low on our list of concerns. We've narrowed down most of everything, but does anyone have any input on what we're leaning towards?
KendoUI is our #1 choice, and if anyone has experience with their react implementation and support I'm very interested in hearing about it.
The alternatives we're considering are BlueprintJS, PrimeReact, and SemanticUI. Is there any reason to even consider one of these if the company is willing to pay for KendoUI?
Other than that, we're trying to decide between Bit.Dev, StoryBookJS, and React-Styleguidist to build their application style guide and provide implementation/ documentation. We're most concerned about onboarding learning curve and versioning, for when they need to add or alter things in the future, and of course how the components are implemented. Any input there is appreciated.
Thanks!
1
u/crespo_modesto Jul 28 '19 edited Aug 02 '19
When you pass an iterated item from state into the same state as a property, why does modifying that property affect the "copied" state item?
eg:
state = {
list: [ thing ]
thingCopy: null
}
// click on thing in UI, set thingCopy = thing from list
then editing thingCopy also edits thing... I would have thought it was a copy of the value but not linked eg. separate
Here's a of my UI. I have a state that loads the row, clicking on the row loads that entry into this popup and uses event to pass values from input into state... I'm just confused why that affects the original state that rendered the individual item. It's going to be a popup overlay when it's styled. When I update state in the onClick handler I only set the "copy" eg. thingCopy which is rendered back into the top inputs
1
u/djingrain Jul 29 '19
Okay, so idk if this is a beginner's problem or not, but this is the error that I am getting when I run
npm start.Here is my package.json:
Can anyone explain what is happening and how I go about fixing it?
1
u/[deleted] Jul 30 '19
I'm trying to use `filter` or another array method to check if an object exists in an array. If it does exist, I want to alert `Already Exists!`. If not, I want to push to the array. https://repl.it/repls/StickySpeedyEmbeds I've tried variations of `filter`, `find`, `includes`, but all of them either push to array for all values or fire `Already Exists` for all values, so I think there's an issue with my if/else logic, just not sure what.
1
u/w1nstar Jul 30 '19
Where in the react app should I hold an instance of a class, that exposes methods used by many components?
I have to implement a third party class into my reactjs app. This class is an api consumer of sorts, made to be able to consume a third party backend. I have to initialize it (meaning instancing it's not enough), and it has methods like add, delete, read... It's like an axios client, but for this particular backend.
I come from angularjs and I'm finding difficult to abstract myself and think on how to implement it. If I make it into a HOC, it gets initialized every time it's mounted, and the initialization is resource costly.
Ideally, it should be initialized after login since it needs the token, and be available to any component that needs to operate with the backend.
Thanks in advance for your insight.