r/reactjs • u/timmonsjg • Mar 01 '19
Needs Help Beginner's Thread / Easy Questions (March 2019)
New month, new thread π - February 2019 and January 2019 here.
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?
π 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 or ping /u/timmonsjg :)
1
u/watchscss Mar 03 '19
I use Netlify to host my static home page, but I've got 3 react-app that I want to show off. How can I do this?
Idea: Start a new repo, a pre-made 'Create-React-App' which installs all the React modules. Then I can upload my apps in separate folders. Will this work?
1
u/Alpub Mar 04 '19
I have 2 API files which export dataPromise and dataPromise2, and in the parent component, I have the fetching method which is =>
I would like to add 2 buttons, each of these buttons will change "dataPromise" within the fetch method so that I can switch between both APIs on click. and i only mean "dataPromise" as a string not as a promise or as an array object. I'm not sure if state is the right approach or should it be ${}, all I want is a function which can replace it with a string/const or whatever it is that can be "dataPromise" & "dataPromise2", a function which csn be used onClick of the button, so that if i clicked on button 1 it will stay dataPromise and btn2 will make it dataPromise2 and button 1 will return it dataPromise and so on, thanks..
1
u/khgdwb Mar 04 '19
I'm trying to work with react-dnd (a react library for drag and drop functionality), is there a way to make it achivebale with react material-UI ?
1
u/javascript_dev Mar 10 '19
Can you guys advise me on common types of websites you make? I want to have another project in mind after I finish the e-commerce website I'm working on.
1
u/ladypalutenta1231 Mar 11 '19
Imagine this scenario:
React App with Email/Password login. Once you click submit, I sent a POST request to my Golang backend.
Golang backend sets a HTTPONLY cookie, javascript can't see this information. How are you guys handling this scenario? Everytime I revisit the root home page, I would ideally like to ask myself "Do I have a cookie?" If I do then skip the login phase else show login phase. Thank you
1
u/Funktopus_The Mar 11 '19
I can't seem to get analytics working on my react site. I've installed the react-ga component via npm, then added this code to app.js
'UA-MYUNIQUEID-1' is replaced with my real tracking ID, obviously. But my analytics account still shows now activity, both on localhost and the server.
Can anyone see what I'm doing wrong?
Thanks
1
u/SuperRoach Mar 12 '19 edited Mar 12 '19
I feel like I'm getting there! writing a sandbox helped minimize the code while still keeping multiple components intact.
https://codesandbox.io/s/503578ozl
In this sandbox, you click the bottom button and a drawer slides in, thanks to the toggleDrawer function:
How can I call or do the same thing from an entirely different component? I would like to be able to Call the Drawer from ListItems when I click on them as well.
1
u/tubehacker Mar 12 '19
I'm using react with redux. How do I access the store state once it has been modified by a reducer? Do I need to force the component to re-render somehow?
What if I want to get that modified state back into the component? Is it just a one shot deal? Like you get the state one time and then you have to entirely reload the page to get access to any state changes that occurred? Is there some function I can call that just gives me what is in my store's state or is mapStateToProps the only way to get state values into the component? Could I hook up a button with onClick that console logs whats in my state whenever I click it?
1
u/BorderCollieFlour Mar 12 '19
What is the state of the art react architecture?
Is it still something like React/Redux/Reactive programming? I know this is a subjective question but would like to know your thoughts, especially if theres been recent developments in front-end paradigms I'm unfamiliar with.
1
u/schmadboi Mar 13 '19
Greetings hackers. Beginner in ReactJS here. I'm currently playing around Spotify API and React Responsive Carousel and well, they work great accordingly on their own ground but I stumbled into a dilemma and ran out of ideas on how to solve it out. Basically, the React Carousel's property that I used i.e.
<Carousel onClickItem={() => this.getPlaylistTracks(playlists.plist_id[randNum]) }>calls a handler whenever a carousel item is pressed. The thing is, I want to pass the same content corresponding to whichever item is selected. So for example, playlist1 is selected from the carousel, the onClickItem shall then pass the playlist1's id to that handler... But I cannot reproduce that considering Carousel's onClickItem seemingly represents the whole package of each items.I've placed the snippet here: https://codesandbox.io/s/x3yo907jmz
What would be the best approach to tackle this?
Any help would be very much appreciated. Thank you in advance for your kind help.
1
u/GCalamita Mar 13 '19
What is the list of function, methods, properties and reserved words of React?
1
u/Ghost1914 Mar 13 '19
Is there a good site that explains all the different reacts? Trying to build my first web app, but I see all these different react extensions and have no idea really what they do.
1
u/Money_Macaroon Mar 13 '19
I've just deployed my app to Heroku, and I realize now that local changes don't go into effect unless I push them to Heroku master, so I can't really test and observe quick UI changes like I can on localhost where changing something and saving causes a reload/re-render. Is there a way of avoiding doing tons of commits/pushes just to tinker with styling and the front end a bit?
1
u/cheriansabs Mar 14 '19
I am integrating Uber apis with my react native application. On one of the screens I load the Uber trip map in the web view. This shows us the map , source and destination pins as well as the location of the driver in the web view. This view constantly changes depending on the location of the driver
My application hangs while showing this uber trip map in the web view .
Not been able to figure our what could the issue be. If i load any you tube urls in the web view the application works smoothly. any pointers to solve this issue would be great
1
u/einsoft Mar 14 '19
I often use the Twitter bootstrap, mainly because of the grid.
I am learning Reactjs and a doubt arose as to the use of both together.
Initially I simply went in the /public/index.html file and inserted the meta link to the Bootstrap CDN and when I need to use inside a component, I just declare the class within the tag "className", so far everything is ok on my initial tests.
I ask: I'll have any problems on future using it that way?
1
u/CptShiner Mar 14 '19
Hey reddit.
I'm learning webdev and react and I'm working on my first react website right now. It's a very classic eCommerce website. On the backend, I have express and mongoose.
I need to fetch products and display them on different pages. On the Home page I will need to display only a few products, like the top rated or last added. I will also have a dedicated page to show every products (many 100 prods), where a user will be able to filter and sort through them. Finally, each product will have his own page.
Should I Fetch all my products only once and share data through components ? Or should I separately Fetch the data I need for each component ?
How should I proceed if I want to display like a spinning animation while I'm fetching data ? I guess I'll have to use ComponentDidUpdate ?
Thank you guys :)
1
u/ozahid89 Mar 15 '19 edited Mar 15 '19
Hi all. Angular developer here looking fir guidance. I need to develop an app in React therefore my interest in this library but I was wondering if there's any guide somewhere for someone like me. Example: equivalent of some things in React compared to Angular. So I've watched the crash course and I think React is quite limited.
I am having problem with the following :
I got lots of question. Apologies in advance. Hope for some guidance.
Thanks
1
u/Grrrucha Mar 17 '19
Hey guys,
I'm learning react and was wondering if someone would be so nice and review this component for me: https://github.com/MichalTomczak/moodiary/blob/master/src/containers/DatePicker/DatePicker.js
I've cleaned it up just now but I'm wondering what should I do now with it?
Should I create a separate components for returning selectors and buttons (because DRY) - I've been told recently that DRY should not be treated like religion and you sometimes should repeat yourself.
I'm under impression that this component got way too big and I should break it down but I'm not sure how. Any suggestions are welcome
1
u/slowsad Mar 19 '19
Hi everyone,
As a practice project I am working on a site that will have it's own little CMS for managing/posting blog posts and other things. My plan (which is currently not working) was to have two major wrapping components. One for the Website
<App />and one for the admin part<Admin />. Then, based on the url I want to pass the suitable component as an element to theReact.Dom.renderer().Here you can see how I set it up: https://jsfiddle.net/7jpx0b56/1/
My problem is that only admin route that works is the
/adminroute. I can see that because the page has thebackground-colorthat I gave thebodyin css and also, becuase the<Navigation />component does not show. However if I go to/admin/blogthebackground-coloris gone, the<Navigation />component shows up and is telling me that the page does not exist. I can only half rationalise what is going on. The navigation and the error message are telling me that it loaded the<App />component but why is the css gone at that point? It's like the site has been loaded outside thebodytag.I tried modifying the
location.pathnameto/admin/*hoping that the star would account for anything that comes after the / to allow nesting.I would really appreciate some help and someone explaining to me what I am doing wrong here.
Cheers!
1
u/ovulator Mar 20 '19
Can someone explain this syntax to me, from react-dnd (drag and drop module):
So I'm "wrapping" the class Module with the DragSource component?
But I don't see any similar syntax on the export documentation:
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
What exactly is
1
u/dggg Mar 20 '19
Which Udemy course would you recommend? Looking to learn more about Functionnal Components / Hooks and Context. Also, we're using Mobx at the office but learning Redux is not a bad idea ! I'm looking at these:
Thanks !
1
u/CafeRoaster Mar 22 '19
I have a few input buttons being used in a form to allow users to make a single selection. When the user clicks that button, it should:
valueof that element in stateI've got the state working just fine. That's easy enough. However, I'm having difficulty understanding how I could make it so that only one element (the element most recently clicked, and thus the element who's value is stored in state) has the
selectedclass.I understand why it's not working currently β any of the input buttons that are clicked will store in the state its value, as well as its class. Since they're all looking at the same state, they all get the same class.
Here are the relevant bits of my code:
I've thought that I could just create a state key for each separate item, but I wonder how this would look to professionals, and I don't want to do something one way that could be done a better way.
1
u/salty-seahorse Mar 24 '19
I'm looking for some more projects like these https://reactjs.org/community/examples.html that I can use as a reference while I build my own copy of the project for practice. Any suggestion?
1
u/Verthon Mar 25 '19
Hey I'm using Router.js with all routes as my starting point in index.js. Can I make a route outside of Router.js?
What I'm trying to achieve is to pass props from EventItem.js to Event.js (Those 2 components are not related to each other)
https://codesandbox.io/s/0x83zz0jmw
1
u/ericnr Mar 25 '19
I import signin.css to SignInPage.js and the body's background color that I want only in my signinpage is applied everywhere.
I'm also confused about how I should organize my CSS in general, though styled components has been very handy when it comes to that since I've started using it.
1
u/mustafazc Mar 26 '19
Has anyone done a react integration with Apple Pay/Google pay on web ?
Can't seem to find any resources on the topic.
1
u/Mazic_92 Mar 27 '19
Hello, I am new to react and web development in general. I've been self-teaching myself programming for little under a year. I'm looking for feedback on some code I have to see if I am going in the right direction, or if what I have done so far might be bad practice.
To explain I have a Navbar that when I click on one of the buttons it changes the state of my Main Page content. I have a bunch of methods that change the state. Then I use props to pass those methods to the Navbar. Finally, I am using conditional rendering to , based on the state, display the components I want displayed.
Mainly I am wondering if I should do something different than have a bunch of methods to change a single state and having to bind all of those methods. It's a really straightforward approach and from what I can see doesn't mess with performance at all. Just looking for some advice on improving.
So this doesn't get any longer I'm putting the code into a code sandbox, it won't run on the page since nothing is hooked up. But it has the code that functions on my webpage, so assume everything works as is. https://codesandbox.io/embed/5mx04yqyl
Thanks for taking the time to look at this, sorry it's so long haha.
2
u/badboyzpwns Mar 03 '19
Is creating a component like this:
const Body = () => {}
The same as:
class Body extends Component?
2
u/RedditAcctsInLrgAmts Mar 03 '19
Is there a best practice for enabling absolute imports in typescript?
I'm writing an app using create-react-app. I just switched to the version that supports typescript. I want to use absolute imports in my typescript files.
I'm trying to import components without having to type the relative pathways, e.g. '../../../actions'. I have this implemented for my .js files and it would be nice to keep import paths consistent between all components
I have found a few pages that describe various ways to enable absolute imports in typescript. Some seem to involve turning off useful features of typescript, and others require installing plugins. What is the best way?
2
u/watchscss Mar 03 '19
[Redux]
How much can I store inside it? Will storing too much cause slowness? I have an array of 30 items, (slightly sensitive data), is is a good idea to place it the global store... ? Thanks for any help!
2
u/seands Mar 04 '19
Let's say I want to add a sidebar widget to a current website not fully built by React. And it has a div with class "sidebarContainer" in sidebar.html. Is this how I could inject into it:
My main disclarity is on how to change the targeting of the html file to be injected into.
2
u/TheMegosh Mar 04 '19
I'm working on my first moderately sized project with React using Material-ui and SCSS and feel really unsatisfied with the way styles are done. I've traditionally designed components around having a ".componentName" className in the top level of a component and imported a SCSS file within the component. This has worked well until I started working with material-ui.
I've found that the library's style tends to override my SCSS styling and I've gone with an approach of using a style object within a component wrapped by the withStyles HOC. This just feels really weird to me and completely clutters the otherwise simple components. It also has an inherent lack of autocomplete for styles defined in js. It also adds some awkward behavior overriding the default styling for body and text color, for example.
Are there some patterns I can use to make these things feel better to work on? I'm just stuck with the feeling that this everything-in-js approach does the opposite of the separation of concerns idea.
My project is here if you're curious: https://github.com/themegosh/Split-It (some components are scss, others are inline)
2
u/aortizoj15 Mar 06 '19
Hello everyone! I was wondering where I can find react course recommendations? I am currently looking for a react course that is updated with hooks. I've seen some courses on Udemy but I am afraid they will be outdated. Any recommendations? Thank you, any guidance appreciated!
2
u/seands Mar 06 '19
I understand NodeJS to be the runtime environment on the back end, for ExpressJS to be able to interpret Javascript for example.
Why is NodeJS even used on the front end? My thinking is it must be purely for development, allowing npm to run various scripts including the build script. I believe once built then the runtime enviroment is the browser (for the built files). Is that accurate?
2
u/[deleted] Mar 23 '19 edited Mar 23 '19
Hellow my dudes :D
I'm trying to improve my code organization, to achieve that I'm trying to use SCSS imports. Basically I'm doing this:
According to https://facebook.github.io/create-react-app/docs/adding-a-sass-stylesheet I should be able to do this instead:
Since
stylesis a folder undersrcHowever, this does not seem to work:
This happens both when running Storybook and the regular React Run.
On
package.jsonI have these relevant configs:And
.envhas this:Any tips on how to avoid paths relative to current folder? Like on my first example, and instead use them relative to
src/? Thanks a lot :)1
u/Giant_Maeno Mar 19 '19
So I've set up a React environment a few times, and it was a giant pain to get everything working together but I managed to to do it.
Now I've started a new project with Create React App and it's blown my mind how it just seems to work immediately. I knew that using it would put some limitations on the complexity of the project, but right away I see that it doesn't allow you to create subdirectories in the /src folder, which I know I'm going to want to do.
So is it a viable use of CRA to just create an app, make sure the environment is proper, and then eject it (it is called Create React App, after all)? Or is there some other benefit it would provide that I'm not seeing, that would be worth the trade-off in customizability?
1
u/cag8f Mar 25 '19
Hi all. I just got started with Create React App for Windows and I'm wondering how to save my work and shut down--I think I may have missed a step. I've saved and shut down everything, but Git Bash is still open with a running process (screenshot). Did I miss something? Here is what I've done so far:
npm startwhich opened my browser tolocalhost:3000. I was able to see my new edit.But now Git Bash remains open with a process running. What's the proper procedure here for a graceful shut down?
Thanks in advance.
1
u/seands Mar 01 '19
For anyone using styled components, is something off with my CSS grit template? It does render 2 columns at the breakpoint but it doesn't flip the order of the children (deckSection continues to be 1st)
1
u/matt2ray Mar 01 '19
Is there a good code example of a use-case for using props with 2 or more components?
1
u/CHRlSFRED Mar 02 '19
I am currently working on an NHL Fetch API project and I would love your feedback and expertise.
First, if there is a way to shorten this code or consolidate it to a few separate components, I am interested in hearing more. I am having difficulty pulling more data from the API as I stated in my stack overflow question below. If anyone can be of assistance, I would greatly appreciate it.
https://stackoverflow.com/questions/54936187/nhl-api-fetching-url-of-all-player-stats-on-a-team-in-react
1
u/jimxyoonique Mar 02 '19
Just implemented a Stripe API into my little project. Is there a way I can retrieve how much I got in the Stripe account and display it or would it be better to query it from the database? Thanks!
1
u/NickEmpetvee Mar 02 '19 edited Mar 02 '19
[Using React 16.4]
Can anyone point me to a guide on how enable a component to be a consumer of more than one one context? I can successfully integrate multiple context providers at the top level, like: https://www.reddit.com/r/reactjs/comments/aue2sz/multiple_simultaneous_contexts. ). I'm finding the consumer part tricky.
The approach I'm using is to create a folder for the component (e.g. src/components/ComponentOne). In that folder I have two files:
The index.js looks like this, and it successfully enables ComponentOne to access the referenced context element
somePropFromFirstContext:However if I try to apply a second context to it like this, I get the error listed underneath the code. Scratching my head... and hoping it might just be a syntax thing.
ERROR:
A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.1
u/[deleted] Mar 02 '19
Hi all,
I am using Lubuntu Linux, and am coming across an error message in my React app (running in localhost:3000 in my web browser) when trying to use Font Awesome icons in my React app. .
I followed these instructions on the Font Awesome website: https://fontawesome.com/how-to-use/on-the-web/using-with/react
This is the error message displaying in my React app.:
/home/rizwan/node_modules/@fortawesome/react-fontawesome/index.es.jsModule not found: Can't resolve 'react' in '/home/rizwan/node_modules/@fortawesome/react-fontawesome'Within my React app, here is the code in my index.js file within my src directory: https://dpaste.de/2kwA
And here is the code within my app.js file, within my src directory: https://dpaste.de/TbtY
And this is the code within my react-fontawesome file (directory path: /home/rizwan/node_modules/@fortawesome/react-fontawesome/index.es.js) : https://dpaste.de/2N21
Apologies for pasting this much code, but I do not know where the error is and think it might be easier to show you the scripts so that the error can be seen .
I have googled the error message, but cannot find a result that contains this error message, and the results that come up contain too much technical jargon for me to understand (I only started learning to code in October).
Thanks for your time guys :)
1
u/Kaimura Mar 02 '19 edited Mar 02 '19
I'm currently working on a todo list and everything works so far - but now I wanted to add filter buttons that filter the todo lists: for example "all", "finished" and "remaining" buttons... each of these buttons has a onClick event calling my filteredList function.. but I have no Idea how to make it actually work inside that function :/
my function looks like this right now:
So the onClick on my "finished" buttons transmits the parameter "finished" - it works when I only click on the "finished" button but if I click on the "all" button afterwards the todo list never reappears in its full glory since I overwrote my todos state object with the new filtered array...
How do I solve this in a smart way? My first (not so smart) thoughts were to introduce 2 new state variables like the boolean 'isFiltered' and another todos object called 'filteredTodos' but then I have to initiliaze ANOTHER state object with everything I received via the api call to fill my todo list with some entries :/ Probably bad practice...So what do you guys suggest for filtering my todo list? How do I go about it in a smart way?
1
u/ryangraves18 Mar 03 '19
Hey guys so i'm a big newcomer to javascript and react so any advice would be great!
I'm creating a movie selector by using MovieDB to get a selection of films but what i'd like to do is have a button next to each film that the user could click to add a film into an array which I would then like to have another button at the top of my app which then picks one film for there array, sort of works like a programme to help pick a film to watch.
Any idea how i could go about this? Thanks in advance!
1
u/Alpub Mar 03 '19
I've built a menu catalog which fetches products from json, inside itemList.js the state items is where the first product list come from, the state items2 is for the second product list, the state activelist is will be either items or items2 based on the button click, and menuI is where the items category are fetched from the json in the file Categories.js.
I am trying to make the categories also change just like how the items changes on the button click.
Live Snippet: https://codesandbox.io/embed/pk3w0y0pom?fontsize=14
1
u/[deleted] Mar 04 '19
Roughly under what circumstance does the cost of running comparisons when memoizing functional components out weigh the performance gain? Is it just a question of how many props each component accepts and how many nodes the component renders? For example, if a component takes one object as its props and renders 20 DOM nodes would be better use case than a component that takes 6 props and renders one?
For example,
({movie}) => [some large component that defines a lot of functions and renders a bunch of styled-components, but lets say it is also a leaf]
vs.
({a, b, c, d, e, f}) => <span>{a+b+c+d+e+f}</span>?
How performant are render calls? It seems to me that running a reference check would almost always be faster than calling a bunch of React.createElement. Can anyone give an example of when excessive use of pure components led to worse performance?
1
u/yourbank Mar 04 '19 edited Mar 04 '19
since hooks are used in stateless functional components, what is the idiomatic way to prevent re rendering since the handler functions are redefined each render?
tslint rule screams when you try put lambda functions within JSX so the only thing I can do is disable this rule and accept that this is just the way hooks are meant to be used which looks like it according to the docs https://reactjs.org/docs/hooks-faq.html#are-hooks-slow-because-of-creating-functions-in-render?.
Eg theres no point creating the 'handlerXXX' functions since it just adds more noise to get around the tslint no lambdas in JSX rule since these functions are recreated each render anyway.
Any ideas?
1
u/[deleted] Mar 05 '19
I have a Next.js question for ya'll. what is the difference between the withRouter way of getting params from the server.js vs the getInitialProps method of receiving and handling data?
1
u/[deleted] Mar 05 '19
I have a general web development question for you guys. I have an API I have access to and I want to make a request to that API once every 24 hours and I want that to be the data that populates my website. Then get a new response the next 24 hours and so on. How would I go about this?
1
u/seands Mar 05 '19
Anyone know how to close a menu when someone clicks away? This one only closes when there's a click on a menu item:
1
u/seands Mar 05 '19
Can a style object take number values (for fontWeight, zIndex etc) or only strings?
1
u/[deleted] Mar 05 '19
does a react website need to be server rendered to have a backend?
1
u/alexlpub Mar 06 '19
Ive saw a nested json example by https://codepen.io/mochiron/pen/jrymLG, and i tried to modify it so that it works with my json but it doesnt show any output, here is a live snippet of what i tried to do: https://codepen.io/alpub/pen/PLbKNB?editors=1111
1
u/Detoxcify Mar 06 '19
I currently have a fully developed Next.js/GraphQL website. I am a bit lost in the deploying part. I'm currently using next.js' multi-zoning feature to separate my adminUI and my shopUI. The logic for deploying to one site is relatively easy, but what would I have to do if i wanted to create multiple shopUI subdomains and one adminUI? With next.js' multi-zoning feature I would have to clone each shopUI folder and would access it through mysoftware.com/shopUI1 mysoftware.com/shopUI2. Isn't there a simpler way in which I can "reach" for the base application and than modify it according to tenant needs?
1
u/Jatacid Mar 07 '19
Hi guys,
I'm working on a site which has a /layouts/ file applied to every single page automatically.
However, I want to modify this for campaign pages (i.e remove the header).
Does anyone know of a tutorial or search term I can use to find one? I'm having no luck getting an idea of how this would work.
I know I can create a Layouts.js component, but this site I'm coming into seems like it's using the /layouts/index.js file to define the global header.
Thank you!
1
u/khgdwb Mar 07 '19
Hi, i'm working on a demo react app as an intern.
I wanted to know if it is possible to store react components inside of a variable that is also a react component.
Thank you
1
u/slowsad Mar 07 '19
Hi, I've been learning react for a couple of months now and also using it but there is one thing that still wildly confuses me! How should I best manage my state?
The way I currently do it is that I use the app.js component for routing and handle the state in the components. The components get their own methods and potentially also have child components that the app doesn't know about. For some reason I have a feeling that this is bad practice. Should I let the app.js component handle state and functions for everything and pass it to the children as props? Or is the way I'm currently doing also valid (I mean yeah it works but should I restructure regradless)?
1
u/Funktopus_The Mar 07 '19
Where do you keep your functions? Looking at my app.js file, I can't help but feel all my JSX is nicely tucked away in components, but my functions are just slapped there. I had a quick browse on GitHub and found a few other projects doing the same thing. Is this normal, or does the this link look a bit gross?
Any opinions welcome.
Thanks!
1
u/merkur0 Mar 07 '19 edited Mar 07 '19
In my really simple to-do app, I'm getting 'Invariant Violation: Objects are not valid as a React child' error whenever I click the submit button after trying to write in the input field. I said trying, because for some reason it won't let you type. If you try to type anything in the input field, the only thing you will see in it is '[Object object]'. I can't figure out why this is.
Link to repo
Any help would be much appreciated, as I am currently stuck on this bug.
EDIT: After logging the 'Object' to console, I noticed it's a 'Synthetic Event', which is really weird since it's supposed to be a string.
1
u/snsarma Mar 07 '19
Hi Folks
I am trying to make the text inside a box responsive , the box is responsive but not the text inside of it .
If it is a large number is getting jumbled up and moving outside of the tile and hence making the tile blow up or shrink , keeping the tiles untouched how can I make the text inside of it responsive.
I am using a react bootstrap template with a Statwidget assigned to each tile , Is there a way it can be made responsive?
1
u/[deleted] Mar 07 '19
I'm trying to figure out how to bundle scss styles into my React components so that when a user imports my component from npm, they don't also need to import a separate css file. Is this possible or do I have to extract my styles during the webpack build process and provide the stylesheet separately?
1
u/cstransfer Mar 08 '19
Is using Javascript with react the enterprise standard?
1
u/seands Mar 08 '19
Can hooks replace most class components going forward?
The docs seem to be worded to encourage just that, noting useEffect and the other niche hooks are good stand-ins for lifecycle methods.
I am apprehensive because lifecycle methods allow precise control, but the docs make the point that this also increases bugs which I can respect.
1
u/seands Mar 08 '19 edited Mar 08 '19
If I want to use query parameters in React Router v4, does that mean I'm forced to forgo the exact prop?
My current consideration is how to use query strings on the home page. If I can't use exact on route '/' I'm thinking to move the '/' route to the back of a switch, so that all other routes in the swtich trigger first/have priority
1
u/prshnt Mar 08 '19
Any suggestion for packages for carousel which supports ssr and is lightweight?
1
u/javascript_dev Mar 09 '19
In the code below, only the button returns a non-null state value. Does useState only allow access to state in the return? I don't recall class components having a state access restriction like that.
1
u/rcklmk_id Mar 10 '19
I don't quite understand Next.js and Gatsby. What advantages do they bring as compared to using plain ReactDOMServer..?
1
u/badboyzpwns Mar 10 '19
So I used npm create react-app to create my react project.
They gave me an index.js file and an index.html file.
My Index.js file has this code:
How does my index.js file know to use the 'root' element in index,html ? I don't see any imports or anything that relates to index.html
Also! for now, <App> contains all the components of my main page. I'm planning to create a 'registration' page. When a user click somethings from the main page it will lead to the registration page. I'm going to guess that I need to create a component that will replace <App> and somehow I need to render
How would I do that though?
1
u/[deleted] Mar 10 '19
In the return statement of React's render function, I would like to use multi-line code within curly brackets, like this:
Which doesn't work:
Unexpected token, expected "}" (13:10)Instead I'm forced to have multiple lines of brackets:What's the common way of doing this? Thanks
1
u/SuperRoach Mar 11 '19
I feel like I'm over thinking this... In short, clicking on a a list Item, I'd like to use a drawer to show the details of it (passing an ID across between them so I can use an API to load the stuff needed) .
I'm lost at what I'd do to approach this? initially I thought of having an onClick={} on the list item which called something like SomeDrawerComponent.toggleState(id) .
Whats the normal way people are doing something like this which I thought would be pretty common?
1
u/javascript_dev Mar 11 '19
I'm having a tough time trying to reason about removing a state setting hook function outside a conditional. It seem you need a conditional inside a useEffect() to setup default values. Can anyone advise on how to fix this to have
setSelectedSku()comply with React's rules for hooks?1
u/NickEmpetvee Mar 11 '19
React 16.8
Database Postgres10
API PostgREST
I'm running into some frustrating newbie errors...
I'm using a great drag and drop library called react-beautiful-dnd. The draggable elements need to be formatted like the below and fed into the library. Essentially, the id value also has to be the key value for the element. I don't know why this exact structure is required, but the library works when you comply with it.
people: {21: { id: 21, content: 'First person' },56: { id: 56, content: 'Second person' },23: { id: 23, content: 'Third person' },},...
In React, I'm trying to compose the
peopleJSON based on the result of an API call and running into some frustrating errors. Can anyone point out what I'm doing wrong or to a reference that can help? Here's what I'm trying in the code:const peopleJSON = {people: {allPeople.data.prop1: { prop1: allPeople.data.prop1, prop2: allPeople.data.prop2 },}}I'm getting errors in my editor for the '
.' in the firstallProcesses.datathat says',' expected.ts(1005)In the browser the error is: Parsing error: Unexpected token, expected ","
If I replace
allPeople.data.prop1with a value like '28' or a variable without a '.' in the name, it's fine. It doesn't like that period.1
u/oldmanchewy Mar 12 '19
I'm really close to my app successfully rendering data from an exciting API but am a bit stuck.
My code so far (minus my import statements):
The example I got this line from (<div key={animal.results}></div>) was pulling img data which is not what I'm going for, how do I render the 'entire object' as data similar to my Postman request?
The errors I am seeing in console are:
Access to fetch at 'https://test1-api.rescuegroups.org/v5/public/animals/breeds?fields[breeds]=name&fields[species]=singular,plural,youngSingular,youngPlural&include=species&options=meta&limit=10' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
and
Uncaught (in promise) TypeError: Failed to fetch
Obviously the second error looks like it can be solved by resolving the first one. So I'm trying to figure out how to solve that CORS policy control check problem as well as how to properly render my API data to the div with the key animal.results.
Any tips are greatly appreciated, the CORS stuff in particular seems to be taking me down a rabbit hole related to proxies which feels wrong.
Thanks!
1
u/javascript_dev Mar 12 '19
Is there any way to create a React Router v4
<Route />that looks like:Where the 1st route param is always the main category, the last is the product, and a variable number of middle params are sub categories?
If there is not, I think I'll need to put 5 of these in a switch with the longest one first. That way the first to match all route params will handle the route. Kind of wet that way though
1
u/Barrel_O_Ska Mar 12 '19
Not sure if this belongs here or in its own post but basically I am following this guide online to do a simple api call that gets a bunch of user images:
https://blog.hellojs.org/fetching-api-data-with-react-js-460fe8bbf8f2
Now you can see the results and how he styled it. Not sure if this is best answered here but how once I have the images in and array would I access and style them as is done in the image provided?
https://imgur.com/EeIuSoq.jpg
I feel like I'm at a complete loss as how to do this without limiting the the amount of pictures being pulled back and rendering the same component multiple times.
TL;DR: How do I make an array of images the background for my site and fill the screen?
1
u/snsarma Mar 12 '19
I have been working on a react app for a while now and have googled enough things to get the current issue of mine resolved.My current app has an issue when I refresh the page or click on back button . On clicking the page refresh the sidebar and header components are not getting reloaded where as just one component of the page is getting refreshed
Tried localstorage , componentwillUpdate and so forth but to no avail , I even tried a way to detect the refresh page event or back button even by having to capture the keycode of the button pressed.
None of the above have worked . I need to resolve this. All of the components sidebar,header and main page needs to be reloaded and not just one of the two components.
How do I resolve this ?
1
u/Alpub Mar 12 '19
I have a mapping function which shows JSON values into checkboxes, I'm trying to add the children of these values as checkboxes under the current checkboxes, below is how the json looks like, I have Side Collection 1 and under it there is children (side 1 and side 2), what I tried but couldn't do is add 2 new checkboxes with the new values (e.g. side 1 and side 2) under the current checkbox with the current value (Side Collection 1), the current checkbox values are passed as props from Checkbox.js to Itemlist.js where the fetch/map happens. Would Appreciate the help.
Live Snippet: https://codesandbox.io/embed/jmmyxzor5?fontsize=14
1
u/tubehacker Mar 13 '19
Listening for Props Changes
What is the best replacement for componentWillReceiveProps?
I am using redux and I have a component that needs to listen for an update to props coming from mapStateToProps to verify that some data posted to the server. Once the props are updated I have componentWillReceiveProps run a function to let the user know that their data successfully posted . The componentWillRecieveProps method works perfectly for this but I heard it will be deprecated soon which is unfortunate since its so easy to use.
I am trying to use getDerivedStateFromProps but its difficult to work with since I need to run some class methods when props updates and you have to turn your class methods into static methods to use and then you have to call them in the returned object and you can't use setState and you can only return an object once. And I'm sure there are more issue but that's as far as I've gotten before coming here to see if something else will work better.
is there some easier to use life-cycle method that would work?
1
u/janitor93 Mar 13 '19
Maybe someone did it. Can I use H5P Plugin in my React app? Without any CMS?
1
u/Alpub Mar 14 '19
I have a function which triggers children checkboxes once a checkbox have been checked, and the values of these checkboxes are mapped from a JSON. The main checkboxes (highest order) and all the children checkboxes under them are shown on check, and i am trying to show the children of those children of the main checkboxes show on check too but i cant seem to get it right.
The checkbox values are passed as props from Checkbox.js to Itemlist.js where the fetch/map happens. The mapping path of the targetted checkboxes is added in Itemlist.js as const selectedMod, ive tried to include it in the existing mapping function to show all checkbox levels together but it couldnt work it only works if it was mapped alone instead of the current mapped path which is const selectedItem.
React Live Snippet: https://codesandbox.io/embed/zw1pn9702p?fontsize=14
1
u/Alpub Mar 15 '19
I have made a selection limit function which ensures that total checkbox is above min value and under max value, these values were taken from the JSON which the checkboxes are mapped from, now the selection limit works, but I want to add another validation function to show warnings, maybe using onblur, but I am not sure how can the same function can be translated into an onblur validation function. for example where if someone unchecks , it shows on the console that you need to select a minimum of 3 until 3 is checked, same logic as selectData(). any ideas would be appreciated.
**Function**
Full Code: https://codesandbox.io/embed/48o2jo2500?fontsize=14
1
u/Verthon Mar 15 '19 edited Mar 15 '19
Hey I'm working on my app(Firebase + React.js) and I'm trying to load data from Firebase in ComponentDidMount(), however data loads only when I type something in searchbar. Thanks.
Full code: https://codesandbox.io/s/0x83zz0jmw
1
u/oldmanchewy Mar 15 '19
Hi! I'm learning to render API data but my code is starting to look WET and not very scalable.
My goal is for the user to see a column of dog elements(<div> I assume) by id, and have the corresponding attribute elements render as children in the 'parent' dog. Right now my render function looks like:
As you can see this results in a div of dog names followed by a div of dog genders, etc rather than the dog by dog outcome I was hoping for. It's also really repetitive as I add more attributes to each dog, and I need to anticipate rendering hundreds of results. Any suggestions on how I need to think about this differently?
Thanks!
1
u/Alpub Mar 15 '19
I need any advice on my code, I have a function which triggers children checkboxes once main checkbox is checked, and all these checkboxes are mapped from JSON. The main checkboxes (Highest order) and all of its children checkboxes (2nd order) under them are shown on check and its working great, what i am trying to show is the children of those children of the main checkboxes (3rd order). Basically to show all three orders under each other on check, and add the 3rd order to my current code, so Options Group shows Options, and under Options is what i want to show, which are Option 1, Option 2, Option 3 and so on..
The checkbox values are passed as props from Checkbox.js to Itemlist.js where the fetch/map happens. As I was trying to achieve this, I have been able to show each of these 3rd order checkboxes but each one alone instead of showing them as nested checkboxes. I've tried to include it in the existing mapping function to show them all as nested checkboxes as mentioned but it couldn't work it only works if it was mapped alone instead of the current mapped path which is const selectedItem. while the mapping path of the targeted checkboxes (3rd level) are added in Itemlist.js as const selectedMod, I am not sure how can this be done. should i map it twice at once or should i create another compoonent, testing any idea isnt achieving anything from what i want.
Main Snippet : https://codesandbox.io/embed/6jykwp3x6n?fontsize=14
What I reached for so far to show the targeted checkboxes but individually: https://codesandbox.io/embed/o932z4yr6y?fontsize=14
1
u/Alpub Mar 16 '19
I have made a selection limit function which ensures that total checkbox is above min value and under max value, these values were taken from the JSON which the checkboxes are mapped from, now the selection limit works, but I am trying to add validation to show warnings using onblur, but I am not sure how can the same function can be translated into an onblur validation function. for example where if someone unchecks , it shows on the console that you need to select a minimum of 3 until 3 is checked, same logic as selectData().
Full Code: https://codesandbox.io/embed/48o2jo2500?fontsize=14
1
u/Zz1995aJ Mar 16 '19
In React, when I needed the latest state for a function, I could pass the function as a callback function to this.setState, what is the best practice for this situation in Redux?
1
u/Kyle292 Mar 18 '19
I am building a simple demo note taking application where you can write a title and some text for a note and then save it and create new ones. Here is a picture of what I've got so far:
https://user-images.githubusercontent.com/6385983/53842376-4863dc80-3f6d-11e9-80bd-918153353af6.png
I built it originally in just React, and now I am rewriting it to learn Redux. I've run into a small problem I am not sure how to approach.
Ideally, I want my note editor (the part of the app on the right) to receive props (title, text, id...) of the note I have clicked on on the left, but when I edit the title or text fields, I don't want it to update the store automatically. I only want it to update the store when I click save. I would like to store those props as initial state in the component. I am reluctant to do this because all my research points to this being bad design and/or an anti-pattern. I also don't want to store a copy of the current note in the store and update that either because I don't see any reason for the modified/unsaved version of a note to be held in the store when it doesn't have any effect on any other parts of the app except the component itself.
I don't really know what I am asking for. Basically if anyone has ran into something like this and wants to lend some advice, that would be great.
1
u/Bombuhclaat Mar 18 '19
Out of curiosity after pressing enter on a new create-react-app command...how long does it take to finish for you guys?
1
u/oldmanchewy Mar 19 '19
My create-react-app runs without errors in development (npm start) but deployed to Heroku the API seems to no longer accept it's requests.
I get an 'unauthorized' error from the API in my console and the error at the url it self says:
Unhandled Rejection (SyntaxError): Unexpected end of JSON input (anonymous function) src/Results.js:24 21 | Authorization: API_KEY, 22 | 'Content-Type': 'application/json'} 23 | })
As mentioned the API responds fine without any errors in development. Any ideas as to what I am doing wrong?
1
u/Wahuh Mar 19 '19 edited Mar 19 '19
hey, I'm learning how to implement drag and drop so trying to understand what some of this code is doing: https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableElement/index.js
const node = findDOMNode(this);
This returns a dom element so how can you do the following?
node.sortableInfo = {
collection,
index
}
How does this work? And how can you access this sortableInfo property?
1
u/Bombuhclaat Mar 19 '19
What backend is typically used with React other than Node?
I guess i'm asking what stack is the most common with React?
1
u/doubleBarrelBUCKSH0T Mar 20 '19
Hi, had a couple simp questions quick. Was wondering if it is possible now to incorporate lifecycle methods into functional components. Also wondering what the main advantage points of using hooks is and finally am struggling to grasp Redux in all it's glory. What is the eureka thing about redux that makes it so supreme for handling state? Lastly I'm trying to figure out where the demand for react developers currently is. There doesn't seem to be a lot of entry-level jobs in the mid-west. Would I fare better getting my foot in the door if I moved out to the coast or should I try networking more with other developers online first? I've been learning JS and react for the last 6 months and am just now starting to get into creating/designing my own components that will fetch data from an api and then wiring together little apps just for practice. In other words, I'm starting to get the hang of React but am still bewildered by the power of redux. Feel free to answer any, all, some or even none of these questions. Thank you in advance!
1
u/GabiruAttack Mar 20 '19
If I have an application which uses redux but I don't need every form to be in my store, is a good practice to just doesn't use redux on every component and make API calls directly from some components?
1
u/infinite-chickens Mar 20 '19
I've never used any type of state management. If I'm just looking to avoid "prop drilling" in a new project (e.g. passing props down to components that need them through others that don't need them), should I use Redux or the fancy new Context/Hooks features?
I know the Redux folks insist that it hasn't been made obsolete by the new built-in React features, but would it be overkill if all I'm looking for is a simple way to have a "global state"?
1
u/_ecwalsh_ Mar 20 '19
When using Redux, how should I follow up a request to add or update data on the server?
For example, I have a basic fitness tracker whose state contains an array of recent user weights and dates. In my componentDidMount(), I call the following, which populates my state (via reducers):
Now say I want the user to be able to record a new entry or update an existing one, through a form, and following submission I want to keep my state in sync with the database:
I'm not sure what is the best practice at this point. Should I be dispatching a new set of actions in this second method, of the BEGIN / SUCCESS / ERROR variety, or is that generating a lot of redundant code? Ultimately I want to fetch the user's weight history again, but the addition of new data is a distinct action from the initial fetch, and I'm not sure whether it merits separate action types and reducers. Maybe I'm overthinking things; just trying to wrap my head around the patterns here.
1
u/penukki Mar 21 '19
I'm getting this error on console
Uncaught (in promise) TypeError: Cannot read property 'map' of undefined
..and here's my code:
Any ideas what I'm doing wrong?
1
u/endlesshappiness Mar 22 '19 edited Mar 22 '19
I'm having issues with the img element in react js. I have a component for dynamically handling an image and some other stuff. Sometimes when new props are received it will show the previously rendered image until the new image has finished loading. This is mostly a non-issue when there is a fast connection, but on slow connections it almost always happens. I have tried a few workarounds with this, but I am stuck.
Here's where I am now. When the component first mounts, the img display style is set to 'none' via a this.state.imageLoaded conditional. Then when the image loads the component updates since this.state.imageLoaded is set to true with setState in the img's onload. This works fine on the initial render, but then I can't set this.state.imageLoaded to false as it will cause the image to display: 'none'.
Any thoughts on how I should go about resolving this? Thanks in advance!
1
u/ThrownAwayyzzz Mar 23 '19
This question is more about how I'd organize a project that makes use of both React and ASP.NET Core. I've used React before but am not sure how to best organize these two toolsets for my project.
I am trying to build a very simple web application where the app takes in user input and outputs values based on the user's input. There is no data persistence involved. It's a silly name converter that will convert your name to a different, humorous one based on certain information given for input. It also handles errors like numbers in names, etc.
I need to use ASP.NET Core as the web component to accomplish this, and then use React to implement the actual functionality of the web app. Now this is a dumb question but I want to make sure I've been doing this right. I have never used ASP.NET before.
The thing is, I can't figure out which part of the app is supposed to be done with ASP.NET Core as opposed to React. I've used React before for web apps and originally I implemented everything just with Javascript and React. Where does ASP.NET come in? What am I supposed to code with ASP.NET as opposed to React?
This is probably a very silly question. I have been doing my research but am dumbly not really understanding this part. I have a development environment up and I see the usual Components folders for React/Javascript, and then I also see a Controllers folder that holds C# code which I haven't touched because I haven't really found a need to do so yet. In the example Controller for C#, it has randomly generated weather temperatures that the code then returns to a React/Javascript file which outputs the temperature. Does this mean I could, for instance, have an array/list of items stored in the ASP.NET component that then gets sent to the Javascript component whenever necessary? Should I use the ASP.NET Core to actually handle the conversions and just send the input from the React side over to the ASP.NET side, and have the ASP handle the conversions? What about improper input, could/should ASP.NET handle input checking too?
I want to make sure I am not doing my project wrong because I've been coding most of the functionality, including stored data, on the Javascript/React side. My implementation works of course but I want to make sure I'm using ASP.NET Core for anything it could handle better.
So, for this simple web app that simply takes in user input, converts it, and spits it back...what is the point of ASP.NET Core? How can I properly use and organize it to make a project that is as organized and efficient as possible? Is there something I could use it for in the context of this application?
Basically I want to do this project well, and use the tools in a way that makes logical and organizational sense. I'm not sure what parts of the project are best left to React and which are best left to ASP.NET Core.
1
u/[deleted] Mar 23 '19 edited Mar 23 '19
Why does the CSS in an App.css import have higher priority than component css imports?
Example file structure:
If App.css has something like
and component1.css has
any div in component1 will still have text that is color red.
1
u/watchscss Mar 24 '19
[Redux] How do I call a Action Creator, based on what is in inside the prop state?
Example: I have a component which carries the Day of the week as prop. If it says Tuesday, I'd like to call the the Tuesday action creator when you click the button. Do I need middle-ware for this?
1
u/Verthon Mar 24 '19
[ContextAPI] I ve created CentralStore for having global state, wrapped Router component with Central Store. How to pass context consumer to Component (Event.js) rendered by React Router only?
Live code: https://codesandbox.io/s/0x83zz0jmw
1
u/nerdchavoso Mar 24 '19 edited Mar 24 '19
Can I update a value inside componentDidMount?
for example I'm using fetch API and I want update a variable (whit onChange) which are being using in a template string
componentDidMount() {
const state = this.state.value
fetch(`http://api.timezonedb.com/v2.1/get-time-zone?key=J9X3EOT2EM8U&format=json&by=zone&zone=${state}`)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
})
});
}
is this possible?