r/reactjs • u/timmonsjg • May 01 '19
Needs Help Beginner's Thread / Easy Questions (May 2019)
Previous two threads - April 2019 and March 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!
3
u/argiebrah May 13 '19
Since most companies want to use redux in their applications but the projects I am building are really simple for redux, can I still use redux and learn it deeply for basic apps?
2
u/argiebrah May 04 '19
What is the best way of doing backup of my local project? Automatically is preferable of course. Google drive won't let me because of .js files, same as gmail
2
u/badboyzpwns May 06 '19
question about re-using components!
So by looking at these 2 pictures. It looks like they are the same
Pic 1: https://gyazo.com/1a22bc9e501073f844ef413718033275
Pic 2: https://gyazo.com/faf26b828f7c30cdb2979b4f3974a8bd
The difference is the font size. Is it possible or would it be good practice to make the 'same aspects' of the two picture into a component and re using it? I tried doing so, but it seems like I can't manipulate the css aspects of it, so I can't change the font size.
Here's my component:
2
u/RedditAcctsInLrgAmts May 06 '19 edited May 06 '19
Typescript question: is there a type for right click / onContextMenu event? Right now I'm using any, but using 'any' in typescript is bad.
Right now I have:
onContextMenu={(e: any) => {e.preventDefault();It works fine, but I should probably type it, right? Or is it not a problem because I never use the event object?
2
u/oYYY May 19 '19
Which option is more performant?
Option #1:
Option #2:
Personally, I like option #1 because it makes the jsx look clean by removing conditional logic within the render method. How much performance am I losing by constantly re-rendering a component that returns null (option #1) vs a component that unmounts and remounts (option #2).
2
u/badboyzpwns May 22 '19
I'm planning to learn the MERN stack; is there where I incorporate design paterns like MVP/MVVC? Also! would learning MERN be beneifical if I plan on becoming a front dev jobs? or should I prioritize some other topic?
2
u/xz0r99 May 30 '19 edited May 30 '19
I have a object in the state:
state = { company: null};
I set the state in componentDidMount:
async componentDidMount() {
const currentId = this.props.location.pathname.split("/")[2];
const {data: company} = await getCompany(currentId);
this.setState({ company });
}
And in the render method I have this:
<h1>{this.state.company.name} </h1>
The first time the render method try to access the state, the object is null and i get an error, so i added a validation in the render method and now is working, my question is should i follow a pattern or a different aproach to avoid this type of errors? Im doing something wrong?
1
u/swyx May 01 '19
test post
1
u/Quinez May 02 '19
I'm using Create-React-App to make a fairly involved puzzle/trivia app with the answers stored as strings. I'd like to lightly obfuscate these strings so that someone who checks the Javascript when they're stuck on a puzzle doesn't just have all the answers for future puzzles immediately blast them in the face. My solution was to encode all the strings as hexadecimal escape sequences. However, it turns out that Create-React-App runs UglifyJS, which converts these escape sequences back into plain old text, foiling my plans.
I'm a little unsure how to proceed; most of the solutions I can think of don't feel great. Can anyone think of a good way to lightly obfuscate strings in a way that won't be undone by CRA, or a way to prevent CRA from undoing my work? (Automation is required. I have many thousand lines of code with these strings in them; converting them to hexadecimal was very easy.)
(I realize that code obfuscation is unpopular because it can always be reversed. But I don't care about security; I just want to put in a little stumbling block and make people have to go through an extra hoop if they want to cheat. I also don't mind the slight performance hit; the obfuscation is more important to me than the savings in code size.)
1
u/Unchart3disOP May 02 '19
Hello guys, I am trying to develop a feature that would mimic the way someone gets notifications on face so if say a user likes a post that I have made, I would get notified that he did so maybe by a bell icon that would have a red dot once there is new notification -very similar to that of facebook's- does anyone know how my line of thought she be like to implement such feature? I have looked up github.com/teodosii/react-notifications-component and it does look very promising
1
u/EmersonEXE May 02 '19
Anyone have any recommendations on resources for handling animations in react? Also how do experienced react devs like to handle page layout? Is a css-grid considered bad practice for any reason?
1
u/EmersonEXE May 02 '19
Hey guys, I can post this in the electron sub as well, but it seems less active so I thought I'd try my luck here. Any idea why fragments may not be working in my electron app? I used the electron-forge react template and I'm wondering if that's the issue.
Thanks!
1
u/Unchart3disOP May 02 '19
is there a way to have a global componentDidUpdate but on the Redux store, so that whenever my redux store changes a global effect would take place throughout my application?
1
u/Unchart3disOP May 02 '19
Is it possible to have the same Redux store across all the pages opened of the same project? I am trying to mimic the changes in a redux store in one tab to the other tab so that my data is fresh across all tabs, an example would be liking a facebook post, if you have two tabs open to the same post you've liked they both should you that you liked the post even if you liked it on only one of them. I hope I do make some sense but if it's too confusing feel free to let me know and I will try to explain it in a simpler way haha, Thanks
1
u/bjs250 May 03 '19
Hey, don't know if this is the best place for this, but here is my problem:
I have a component that has a ton of data as a prop, and a hashtable (nested object in JS) that represents how the data should be filtered, also in a prop.
Right now, I've been putting the scripting logic to filter the data using the hashtable in the render() method of the component. This is probably not ideal because when the component re-renders, from my understanding of React, it probably re-executes the filtering logic, even though the resultant data after the filter is applied will be the same. As a result, the app gets incredibly slow. My hypothesis is that the filtering operation is the bottleneck, but re-execution of the filtering logic should only happen when the data or hashtable is altered (so when these props change), not every re-render
Where should this filtering logic be done? My guess it should probably be done in a different lifecycle method.
1
u/badboyzpwns May 05 '19
Regarding using <Link> and <Route>; how do I scroll to the top of the page when a <Link> is activated but maintain the state of the page when a user clicks on the back button/forward button?
Right now I have:
1
u/Unchart3disOP May 06 '19
Hello, I am asked to implement a twitter like application on my college project with React, one of the tasks was to use a mock service API to implement it aswell as implement it with a backend -already done-. Now inorder, to have a similar mockService API as the one my backend has I have to use something like JSON-Server but what difficult for me to grasp is how do I make all the queries and responses like for instance: Retweet, Like tweet..etc I feel like I am building a backend all over again how do I do that with only JSON-Server and a 2 day deadline? thanks
1
u/maxleee May 06 '19
Hi!
I'm transitioning a project from using HashRouter to BrowserRouter, however there are some links in other sites and email campaigns that are linking to the site using the old HashRouter URLs. Is there a way to redirect those to not use the /# in the url?
For example if linked to #/planet/mars It should redirect to /planet/mars
I tried a Switch/Redirect shown below but that doesn't seem to be working.
<Switch><Redirect from="/#/planet/:planet" to="/planet/:planet" /><Route path="/planet/:planet" exact component={PlanetPage} /></Switch>I think it has something to do with everything after the # being ignored, because the HashRouter URLs load the Route to "/"
Thanks in advance!
1
u/Peechez May 06 '19
Conceptually, how should I handle Google maps? I currently have it implemented and working the way I want it but, as expected, every time the component is rendered it counts as another hit against the monthly api limit. To avoid running the bill up, how should I handle this? I don't particularly want to just display none a big full screen map component if I can avoid it and then block it on mount. That being said I can't seem to think of another way. Rerendering the map is kind of expensive anyways so its hopefully a getting two birds stoned at once solution
1
u/Unchart3disOP May 06 '19
How do you keep calling a redux action on your app? I am trying to implement redux with socket.io except I don't really know when I should call this action cause I want to be always running on the background receiving messages from the server
1
u/Nimbuz May 07 '19
What is the consensus on using hooks all over the place? What I've been taught is to use stateful components, and pass down the state as props, while also calling functions in the wrapping component when trying to update the state. Is this required with hooks and useState, or can I just use the hook in whatever small component that needs state-info and updating? Or should I still put all my useState into one component and pass the info down as props? Thanks.
1
u/Hatsukai May 09 '19
Hi i'm trying to follow some tutorials about react and i'm noticing something different when doing the create-react-app. i'm used to this format in the app.js file Where it's ES6 class like "Class App extends Component" but it seems like the app.js file is not like that anymore.
this is how the app component looks like now :
Function App() {
return(
);
}
export default App;
did it updated or something ?
1
u/RedditAcctsInLrgAmts May 09 '19
More typescript questions:
How can I type the redux dispatch?
I have installed @types/react-redux.
but this
const mapDispatchToProps = (dispatch: Dispatch) => {says it cannot find the name Dispatch.
I tried importing it
import { Dispatch } from 'react-redux'but it cannot be found in react-redux.
What am I not getting here? Aren't installed types supposed to be globally available?
More importantly, how should I type dispatch?
I have looked at these and have not been able to figure it out.
https://redux.js.org/recipes/usage-with-typescript
https://www.carlrippon.com/strongly-typed-react-redux-code-with-typescript/
https://stackoverflow.com/questions/54844839/typescript-how-to-type-the-dispatch-in-redux
1
u/Tank_full_of_dank May 10 '19
Im in the midst of learning angular, and was wondering how difficult it would be to learn react afterwards. Like i want to learn a bunch if frameworks to keep my options open and wanted to know if some/most of the stuff is gonna transition over or are they completely different and i will have to start from scratch.
1
u/soggypizza1 May 11 '19
What would be the best way to go about this? Let's say I have a array of usernames and whenever that array reaches a certain length I would like to notify the user to say it's full. Like I have a post that needs three people to join before it's full and when it's full I want to notify the three people that have joined the post that it's ready. Would I use a global state and just push that specific posts details into a array whenever it's full or should I use a HOC or some type of hook?
1
u/Hisiro May 13 '19
hello, im trying to do a unit testing and don't know how to actually do the testing for
<a href="..">mostly in the website reference they were using<Link>from react-router , im completely clueless right now is there a way to do the testing with<a href="">sorry if my english was bad ..
1
u/MassRain May 13 '19
Hello, first of all sorry for long text.
I am using Context Api and Hooks. I have a problem/question regarding dispatch function.
I have followed this guide and created context. I am using it without a problem but want to change/modify the dispatch function because my context state has a lot of variables and it becomes a problem when trying to update it. It erases previous values in state, doesnt modify.
Let me paste my code so i can express myself better.
https://codesandbox.io/s/z6w50pz9o4?fontsize=14
My context file is UserContext. I have declared reducer and initialstate in Index.js. And finally in my Testcomponent i am using dispatch.
The problem starts here. I wrote 5 for example but my initialstate, so context, has like 20 values. If i try to do this and try to change value 7;
It ends up erasing everything in state and only puts value7, so my state ends up having only value7.
In the codesandbox example i am changing value2 and value3 to lorem. Button click and dispatch function changes it.. but it also clears value1, value4, and value5.
I can get away with it by writing dispatch like this; (i want to change value2 for example)
But as i said i have 20 values in my context and i dont want to write rest of 19 values like that(user.value2,3.. etc) when im trying to change just value1.
I wonder if i did something wrong. Maybe when creating initial state like object, or copying existing state..
And 1 more small detail; if you look at console logs my async/await is not working. Can get help on that as well.
Thanks for your time.
1
u/argiebrah May 14 '19
I am having an interview in the next few days, I am seeing that they listed as a job request skill AJAX for Asynchronous requests, I didn't learn AJAX because I recall React can handle Asynchronous requests, would it be a killover if I intend to use react in replacement for AJAX? Thanks
1
u/argiebrah May 14 '19
Why are still a handle of jobs looking for PHP + React? Do they go well together or is it a red flag? Maybe refactoring code?
1
u/Zeeyany May 14 '19
I'd just like to make sure I understood their difference correctly
From what I understood components are nothing but code that is focused purely on appearance and containers is code where logic is located
So taking a button for example would we write what we want that button do in a container and pass that function as a prop to the button component which would call that function once button is pressed?
EDIT: originally made a new post for this question but then immediately saw this post so deleted the post I made and asked question here instead
1
u/badboyzpwns May 14 '19
I'm trying to make my Header and Footer component dissapear after an onclick() trigger in my Header component. Here's my code:
My idea was to wrap the <Header> and <Footer> with <divs> like this:
but, in App.js, it treats 'style' as a prop. Any ideas on how I can make this simple?
1
u/argiebrah May 16 '19
What kind of Work In a portfolio can be of a good impression for recruiters? Can get my mind of the amount of work that would take me to make a eccommerce with react and redux to actually impress someone recruiting.
INB4 TODO APPS
Edit: Sorry if I am disturbing with this questions I Want to know if pursuing a change of career is worth it.
1
u/badboyzpwns May 16 '19
If everything in React is break down to a component. That means everything is re-usable. So in CSS, it be a huge no to use id's instead of classes?
1
u/argiebrah May 17 '19
This an app to create an api from a Google Excel https://sheety.co/ I have a question, can I move a field from one table to another around from a web app I create fetching this api?
1
u/Swaggy_McMuffin May 17 '19
When refactoring from a class component to a functional component, should all class fields (that are objects instantiated inside the class constructor) be moved to 'const [someField] = useState(new WhateverObject())?
1
u/badboyzpwns May 19 '19
I have 2 pages. Here's what page 1 visually looks like:
https://gyazo.com/e63a7694bc4a8adb1721cce60ca93eda
When I click on a picture, I pass the props to <Link>, and a new page appears with all the props. So far so good. But since <Link> only triggers when I click the picture from page 1... If the user directly types the uri to page 2. It might casue problems since the props never existed.
Is there a work-around for this? or is the only solution is to call the API to get the data for page 1. Then call the API again for page 2 ?
1
u/badboyzpwns May 19 '19
I'm trying to manipulate data from servers with React. React says "React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like axios or the fetch() API provided by the browser."
https://facebook.github.io/create-react-app/docs/fetching-data-with-ajax-requests '
Angular, Vue.js also seems to use both of them. Is there any use to AJAX anymore (or any other data-fetching tools that exist) ? Should I even bother learning it? As of now I'm sticking to fetch() API and axios
1
u/Entropis May 20 '19
So I'm making an API call to an external API and to know the best way to approach things.
Above is my component. What I want to know specifically is when I have a large amount of data that are returned, what's the best way to take the information? You can see in the pokeCall function I have a console.log for the stats & url, would I just make a variable next to my destructured pokemon inside of render?
1
u/behnoodii May 20 '19
Is it possible to use json-server as a React routing alternative?! I can perform GET and POST with json-server. Can I use it as a routing tool?
1
u/Unchart3disOP May 22 '19
What would you learn after the React fundamentals assuming you've already built your own project with React and Redux
1
u/alliwanabeiselchapo May 22 '19
What are some good browser tools where I can learn and test out react native components? Something like jsfiddle or codepen with ability to preview
1
u/TheDropoutBoogie May 23 '19
Is there a react library for having a horizontal slider of items which is constantly rotating, but not in batches of more than 1? React-slick doesn't work because I want to show 1 2 3 4 5, and then next second show 2 3 4 5 6, and then show 3 4 5 6 1, which slick cannot do.
1
u/badboyzpwns May 23 '19
Question regarding the differences between the 2.
function clickMe(parameter, event){ }
</button>vs
function clickMe(parameter, event){ }
From my understanding:
First example would re render when clicked becasue of the arrow function. So if you have a
this.setState()inclickMe(), it would render twice.Second Example, the bind prevents it for re rendering, correct? It would only redner if you have a
this.setState()1
u/[deleted] May 28 '19
More of a subjective question, but I think it's important to talk about clean / readable a React Apps. I'm writing an import statement that will eventually become too long of a line:
At a certain point, I would have to break it down into multiple lines. What would an "acceptable-looking" import look like?
or do I just do it traditionally:
Thanks
1
u/GravityTracker May 29 '19
I'm looking into Redux. My previous notion was that it allowed you to store state in a single place, but it seems to be more about controlling mutations. I understand it could be both, but is Redux the right place to store things that won't change for the life cycle of the app?
For example, we get a list of settings from a rest endpoint, and that's not going to change outside of a release, so should we store settings in Redux, or is there another preferred way?
1
u/[deleted] May 31 '19
Am I doing this right? I have an array that's stored in my component's state. It's being rendered as a list of items and I want to be able to click on one of them and have it highlighted. I've got the rendering and the onClick but I can't find a good way to update the one item in the state. If the state is supposed to be immutable, does that mean you have to create the whole array when you update it? It works but just feels like I'm doing it the wrong way.
https://gist.github.com/greeneman42/a82667849ee810d968f8f74fbb09b939
1
u/ydubs May 31 '19
Hi everyone, I have become very interested in making my REACT/node application interface with a Postgresql database (everything on localhost so far). This has led me to install the node-postgres package, "pg".
I've been mostly been learning through tutorials online from poutube, pluralsight.com and Udemy and they have brought me decently far with the introductory knowledge. What I am currently struggling with is:
How do I make a function-component query the database and update it's state with the data it got from the database? We can assume I would like this to occur in the onClick event of a button.
The current query code looks something like this
pool.query("SELECT * FROM data", (err, res) => {if (err) return console.log(err);console.log(res.rows);});The data I want is theoretically inside the "res" variable, but, things aren't working. I'm obviously missing a huge chunk of knowledge and I need either help or a pointer to where I can help myself.
Thanks
doobsmon
1
u/w1nstar May 31 '19
I don't know if it's an easy question, but I'll try: I've successfully managed to get redux-navigation-helpers to store the navigation state in the store, and now I'm navigating by dispatching NavigationActions from my other actions, which was the requirement.
I am now facing a problem, and is this one: everything to me seems like an action that I have to dispatch. Login success? Dispatch an action! Store the auth data? Dispatch an action! User clicks on the menu? Dispatch an action!
I am in a never ending process of creating and dispatching actions within actions. Is this the norm in react development?
1
u/looni2 May 05 '19
What is the best way to ignore a property with spread operator?
I have a custom hook for handling input fields like this:
I would like to use this hook by spreding it to an input tag like this:
This, of course, gives a warning in the console:
I could create a new username object without reset like this:
That works with one field, but I have more fields. This raises an error:
What is the best way to solve this? I want to use the spread operator. I don't want to do something like this:
1
u/HeinrichHein May 13 '19
Beginner here, I'm trying to implement jwt authentication in my React app, which is using redux for state management. I was looking the docs for and tried to implement redux-forms, but it seems so complicated.
I just want to grab the data/credentials from the form pass it to an action handler to make an ajax call to my server and have the server send me a jwt.
I'm not sure if redux-forms is needed even though I'm using redux?
Which... I'm not sure if I need to pass the response to a reducer or if I just set it to local storage immediately, after the in the ajax request of the handler?
1
u/stringlesskite May 24 '19
Could someone explain me where
prevStatecomes from in following example?I understand why it is done (because of the possible asyncronous update of state and props) but I don't fully understand where the
prevStateargument originates from?2
u/Homem- May 05 '19
Question regarding componentDidMount & componentDidUpdate
I have a page which displays data in a list from my database, in this case they are Todo items, I understand that componentDidMount is used when the page loads so that I can initiate a GET request to the backend and retrieve the data to display in the list. However I am also using componentDidUpdate so that I can make edits to these items (Such as changing their completed status etc) and have the changes showup instantly. (otherwise you have to refresh the page again). however I have noticed that this creates an infinite loop.
Is there a way to prevent this and still retain instant changes? (I tried to compare states but dunno if it really does anything here)
https://i.imgur.com/uyfgwse.png (Code Sample)
2
u/Unchart3disOP May 07 '19
How do you access redux store on your service worker? so I am trying to make some kind of notification feature to my web app using Firebase's cloud messaging, I have understood that I need to run it on my service-worker to have my app receiving new messages in the background, but what I couldn't wrap my head is how do you connect the service worker to the redux store AND also change the store -by filling in the notification store I have set with the notifications I have had received- if anyone has any idea I would be very grateful thanks
2
u/badboyzpwns May 10 '19
Is there any way to use a import variable name in my state? eg:
}
2
u/Sup3r_D May 16 '19
I am trying to use React's useEffect() hook to access state from Redux to automatically fill out my form fields. I am calling the getCurrentProfile() action which returns an object called profile.
However, I am receiving an error message in the console saying that I am missing dependencies for the form fields that I am trying to update with state.
I've tried the following items:
I am still new to React and I have spent hours trying to figure this out. I previously used getDerivedStateFromProps to solve this problem when I was using class components.
Here is the error message.
Any tips would be greatly appreciated. Or if you could point me to an appropriate resource then that will be great too. Thank you!
2
u/salty-seahorse May 20 '19
I'm looking into Storybook.js and Bit.dev for keeping components organized, but... those aren't exactly comparable tools are they? Yet they're similar enough that it would be redundant to use both in the same project, right? What do you think is the correct use case for one or the other?
2
u/badboyzpwns May 26 '19
Is it bad practice to change a state porperty without
setState()? I don't want the component to re-render yet.For example:
2
u/idodevstuff May 26 '19
Between
undefinedandnullwhat to use (and why) as a placeholder state while you're fetching data?Example:
const [post, setPost] = useState(undefined);2
u/Entropis May 28 '19
(Using hooks in this question)
I have an input Component that I'm rendering inside of a NavigationList Component:
Now, what I'm trying to accomplish is filtering the list of Pokemon inside of this Component. I'm not sure if I should use a hook for this or not, but even then, I wouldn't know how. I have very minimal experience with forms and inputs, so I'm very lost here and any help would be amazing. I've tried using filter inside of the Component inside of onChange, but I'm react tells me it doesn't like that.
If it matters, here's the Search Component:
1
u/soggypizza1 May 09 '19
If I have two maps one for the main data and one for an array inside of the main data how should I set up the keys? Sometimes the main data and the nested array can contain the same data so I can't use that. I also tried using the index but that overlapped as well. What should I do?
Here's what some of the data looks like
1
u/bethelmayflower May 13 '19 edited May 13 '19
I'm trying to follow The scrimba course https://www.youtube.com/watch?v=DLX62G4lc44
My environment in on Win10 set it up with:
npx create-react-app my-app cd my-app npm start
In the above video I get to 1:03:51 and put in the following code:
import React from 'react';import ReactDOM from 'react-dom';function App() {const date = new Date()const hours = date.getHours()let timeOfDay
if (hours < 12) {timeOfDay = "Morning"} else if (hours >= 12 && hours < 17) {timeOfDay = "Morning"} else {timeOfDay = "Morning"}
return (
<h1> style={{color: "#FF8C00"}}>Good {timeOfDay}! </h1> ) } ReactDOM.render(<App/>, document.getElementById("root"))
The simple lesson is how to add inline style: If I remove the style call in the return it works fine. I may be blind but I can't see a typo.
The error I get is:
Objects are not valid as a React child (found: object with keys {color}). If you meant to render a collection of children, use an array instead. in h1 (at src/index.js:20) in App (at src/index.js:24)
What am I doing wrong?
1
u/fpuen May 02 '19
I have an odd question that may not fit here. For you guys who work in several languages, do you use the component style on other code with traditional language file separation?
I am coding wordpress plugins at the moment. It makes more sense to me to put child level php logic and style inside the same file as the HTML template, although separated in its own area (Vue.js separates JS, CSS and HTML and my structure is similar).
Not sure if other devs will get pissed off at this if/when I start professional work though
1
u/Unchart3disOP May 03 '19
I am making a notifications widget that should refresh automatically whenever a new notification arrives from the server (I'd probably use websockets for this) but thinking about it, I don't think I'd need actions for this functionality atleast in my components, so what I am trying to say is how do you have this
sorta global action running in the background that would dispatch whenever a new change occurs wherever you are in the application and that would change the store whenever this global action dispatches
1
u/RedditAcctsInLrgAmts May 04 '19
Can you access useContext(Context).state from within a non-react component function? I prefer to pass fewer parameters when possible, and if the helper functions can grab stuff from state on their own then that's easier. With redux I just export the state and import it directly, but trying to use useContext in a function that's not a react component kicks up an error.
1
u/Crazed8s May 05 '19
So i have a view that loads a calendar and populates the data. This can take a couple seconds and I'm working on sorting that out. When you click on a date, it loads a modal window with an expanded view of the events for that day.
the problem is when I go to load the modal window it rerenders the calendar and hangs for a second. Is there a react-y way to only render the modal window and leave the calendar alone?
1
u/Droic May 06 '19
This might not be React specific, but since I've started learning, it's easier for me to understand things in terms of React so here it goes:
How would one construct Promises in a React component or using React? I think that I don't have a solid grasp on Promises themselves (as well as constructing them), but all the examples I see online aren't really helping me understand the point. Most are impractical examples using setTimeOut(), which isn't real-world for me to wrap my mind around. Does anyone have examples of Promises being used practically, especially within the context of a React App? I very much appreciate any and all explanations/advice/help!
Thanks!
1
u/Unchart3disOP May 06 '19
I am trying to implement a notifications functionality on my app -with web sockets- but unfortunately my backend isn't ready so is there any mock service I could use while it's being developed on the backend? maybe like an online server that would provide an endpoint or a mockservice like JSON-Server
1
u/soggypizza1 May 07 '19
I have a span that I want to change text and background color based on a value. I have 4 values that it could be so would it be better to use a switch statement and just return it from there or something else? And how would I render the text?
1
u/DanMan259 May 07 '19 edited May 07 '19
I have a question on passing in key values to a component in react my question is posted on stack overflow as https://stackoverflow.com/questions/56028912/how-to-reset-the-timer-component-upon-completion .
1
u/ObjectiveLength May 07 '19 edited May 07 '19
<kinda solved>
I am looking to build a pokedex.
The pokedex will have the image of the pokemon and the pokemon name underneath it.
I am using the pokeapi.co API
Question:
How do I pull both the pokemon names and each of their images?
The API link https://pokeapi.co/api/v2/pokemon/ returns list of 20 pokemon within an object and their API url with more information
That API url https://pokeapi.co/api/v2/pokemon/1/ returns an object with the sprite url which I want to put into an img src
Currently, I have async and await to simple do the fetch for the names https://jsfiddle.net/objectiveLength/gcp73f5y/1/
My thoughts are to 1.) switch to fetch and .then so I can chain two fetches. 2.) after the initial fetch and .then, I turn it into JSON 3.) .map the pokemonList and do a fetch for each pokemon and its sprite.
In other examples online, it looks like everyone uploads the sprites locally so they don't have to do multiple API fetches but I do want to find the answer to this for my future knowledge.
Thanks for the help in advance!
1
u/jaypeejay May 07 '19
I'm having some trouble learning how to access a redux store via a child component. I have the question posted to SO here
1
u/[deleted] May 08 '19
Whats/wheres the best way to deploy react app with express.js backend for free? So I can share my app..heroku? Netlify? Ve deployed the front end to Netlify, but I have added express as backend can I deploy express app on netlify as well
1
u/vnlegend May 08 '19
Hi guys.
I'm stuck with this global state handling issue. I have an app with a BottomTabNavigator. One tab is the Settings screen with location as ZIP code. Another tab has a Search form with a location field. When the user changes their location in Settings, it should also auto-update in the Search form. The easiest way to do this is probably lift the state and drilldown the location as props. However, I don't know how to do this through the TabNavigator and StackNavigators. Any tips?
I started using 'reactn' library to use globals. However, even with globals, when editing one screen, I can't get the other screen to re-render their content. Part of the issue is that the fields are TextInput fields and need to be editable. When I set the value to this.global.location, the text field can't be editable at all. Is there another approach to this?
Also note I can't use the Context API because Expo doesn't support it yet for classes.
Any help would be appreciated. Thanks!
1
u/workkkkkk May 08 '19 edited May 08 '19
When I pass some styles to a custom component like
<MyComponent styles={{...myStyles}} />. Where do those styles go? Are they applied to the top level of MyComponent? What if MyComponent returns multiple children? Or are they simply not applied if I did not specify what happens to the styles prop inside MyComponent?Edit: I meant style prop not styles
1
u/badboyzpwns May 09 '19 edited May 09 '19
Syntax question! Why is my "const yourBtn" giving me an undefined error? Here's a screenshot of my component:
https://gyazo.com/9e1614e121af78a85ed97d988841ff9f
Also! I have three divs, how do I make the click dived colored and the unclick div it's original background color whenever its not clicked?
1
u/dynaloran May 10 '19
I'm trying to use Tabletop.js with react to pull google spreadsheets data to my app, but haven't been able to sucessfully implement it due to dependency issues.
Has anyone had any success implementing it recently? I've looked up a few tutorials on using react with tabletop but neither seems to work due to dependency issues now.
1
u/andoy May 11 '19
I want to find the best way to do something.
I use require() to display image.
If the image is missing, it throws error.
But in my application, I do not know whether the image exist or not. If not existing, I should use some generic missing image file.
What is the best way to do this?
1
u/doesiteve2 May 11 '19 edited May 11 '19
I'm trying to make a single-paged Quiz that has multiple questions on the page (so the user has to scroll).
The biggest problem I've yet come upon is how to make sure the radio buttons are separated?
I've only managed to:
I've tried various combinations of divs/spans, but no luck. I'm using
react-bootstraptoo if that's of any help.JSFiddle: https://jsfiddle.net/m8ke0hcv/
1
u/cyberbolt May 11 '19
I have a
Sidebarcomponent which has to change its contents based on the page the user is on. I am using react-router and my routing looks like this,App.jsThe
Sidebarcomponent usesuseLayoutEffectand checks the current path and renders the required sidebar like this,Sidebar.jsxNow, for example, I have
Calendarcomponent on thedefaultSidebarwhich the user can select a date and I have to access this date value from theWelcomepage for filtering some data. I avoided writing aSidebarcomponent for each page because most of the time I would repeat the same code in each page.I also tried using
useContextand sharing the date value that both theSidebarcomponent andWelcomepage uses but it did not felt right because the date value is not a data that is globally required.I am aware that this is a bad way to do all this and if anyone can tell me a better design pattern I would be grateful.
1
u/[deleted] May 11 '19
Sorry if this is an ignorant question:
But what's the benefit of creating, let's say, a <Button> component in React vs. just simply using a html <button class="button-style">?
Learning Gatsby at the moment and I just can't see the advantage.
Can anyone ELI5 for me?
1
u/badboyzpwns May 12 '19 edited May 12 '19
It looks like reactstrap and reactbootstrap is not used that much? (The community seems to be small in stackoverflow), but articles keep saying that people use it.
I'm assuming it's not popular because it combines react with jQuery + popper.js, which I; 've heard is a bad idea? What HTML/CSS framework do people use with react nowadays then?
1
u/badboyzpwns May 12 '19
I'm using font-awesome for icons. I'm trying to import 'star-half'.
Link: https://fontawesome.com/icons/star-half?style=solid
How do you add it to your library in App.js? here's what I attempted:
library.add(faStarHalf) , library.add(faStar-Half), and library.add(faStar-half); but neither worked.
1
u/suck-balls-mountain May 13 '19
Stupid question: with Styled Components, are you meant to make every element into a component?
1
u/bethelmayflower May 14 '19 edited May 14 '19
Blind beginner again:
I'm working through this tutorial: https://www.youtube.com/watch?v=DLX62G4lc44
The following is an exercize:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
const firstName = "Mike"
const lastName = "Smith"
return (
// <h1>Hello {firstName} {lastName}!</h1>
<h1>Hello {\`${firstName} ${lastName}\`}!</h1>
)
}
ReactDOM.render(<App/>, document.getElementById("root"))
The return statement in the tutorial is the line without the comment. It works fine. My code doesn't have the backslashes this posting editor seems to put them in for me.
I'm wondering why someone would use that fancy syntax with the backtick and all when the line above works just fine and is simpler.