the spread operator {...content} throws a warning: Invalid value for prop `reset` on <input> tag.
The question is how can I maintain use of the spread operator while also fixing this problem?
I feel like it is an easy fix that I am just not seeing. If you wish to see the problem in full and most likely explained better its bottom of this page https://fullstackopen.com/en/part7/custom_hooks question 7.6
The other answer is perfectly valid, but I would caution against actually doing it. I've seen real-world bugs where a similar pattern is used and then in the future someone plucks out another specific field, so now that field is no longer present on the "content" object and doesn't get passed down as a prop. There could also be the opposite situation of more fields being added to content and then needing to be plucked out.
It may seem more verbose, but it's usually going to be better to just explicitly set every prop.
This seems like a case of whitelisting vs blacklisting, and in most cases whitelisting is better because it's less prone to surprising behavior and bugs in the future.
How does rerendering work when setting multiple states? For example when I have a button with an onClick that calls a function that has multiple setState hooks, does it rerender for each setState or does it go through everything and then rerender all at once?
why do you have to use a class for redux-form? I tried building it with a functional component and it re-renders/makes me unfocus the input. These 2 examples below are the exact same code! but I demonstrated both with a class and a functional component.
I've deployed a React app talking to a Firebase Firestore DB using Amazon's Amplify service.
My Firebase API keys are defined in the AWS console as environment variables.
My question is: Is this a secure way of doing this? or are my Firestore API keys and other secrets accessible for someone who chooses to go through the compiled files in a browser?
I found this in the React documentation that has me confused:
WARNING: Do not store any secrets (such as private API keys) in your React app!
Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.
The purpose of a button is to have a clickable thing that triggers some javascript (or a form). You're not allowed to nest clickable things, so putting a Link inside a button is not allowed.
You should use class names to give your link the correct styles.
I'm planning to intern as a junior dev! Is it valuable to learn Testing such as using redux-saga, Jest, etc? (I don't see any job postings specifying that I need to do unit tests, etc) Or is this more of valuable asset for experienced senior devs?
React 16.13.1 (via create-react-app that executed a few days ago)
Implementing a file upload prototype and using a tutorial. The below code yields a POSThttp://localhost:8000/upload/image404 (Not Found) as a result of the await fetch. I've created a folder '/upload/image' under '/src' and '/public' with the same result. Also tried changing the fetch target location to '/' with no love. No special configurations to node.
Also tried with AXIOS that yields
Failed to load resource: the server responded with a status of 404 (Not Found) Huston we have problem...: Error: Request failed with status code 404 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61)
Any ideas?
const api =
{
async uploadFile (nextFile)
{
console.log('processing');
console.log(nextFile.file);
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = nextFile.file;
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
} catch(e) {
console.log('Huston we have problem...:', e);
}
},
}
I have a quick question. I was following the tutorial below to build a multi step form with react hooks. but I don't understand why he uses <div> instead of <form>. and how you can send the data with onSubmit = (event) => {}. Thank you for your time.
I think I will need to use the effect hook to acces the api point to write the data to my database.
Hi, I have a question about this counter component.
I click the button and the value of the button increments. Nice! But after I call setCounter(counter + 1); and callconsole.log("counter", counter);` on the next line, the output is always one value behind. How come? Is there a way to fix this? Thanks.
If I pass function to parent component and call it (without using imperative handle) why can't it access current state of the child component? What is its context? Could someone reference me to the concepts that explain this behavior?
I am trying a fucntion which I declared in a seperate file. When I clikc the button to fire the function nothing heappens can someone explain me what I am doing wrong.
I'm not sure why you wrapped the result in a fragment, or why you pulled the body into a separate function, inside of just doing what I do above, though.
If the className computation was more complex, you can also just pull that into its own variable or function:
Hi, why is it that when you define a function inside of a component class, you don't need to write the word "function" in front of it? Is it automatically assumed somehow when its compiled?
Using react-router-dom and so far can't find in the docs how to create a static link to a specific page in my app. So for example if I have an info page that I put at /info and create a link to it on the main page using react-router-dom, I can click the link to /info and I go there and it works. However if I type http://mydomain.com/info in to the browser, I get a 404.
I understand why it works this way, but I don't know what the fix is, or if there is any easy way to allow bookmarks to work in this type of app.
In case it matters, I'm serving the page using python/django. So when I go directly to the /info URL, I get a django 404.
My only guess at this point is to create a catch-all route handler in django that will redirect to the main page and then somehow have it navigate to that URL after the page loads. Maybe create a template variable that sets a JS variable that the react app can inspect and if it's set go directly to that URL? Seems a bit kludgy so I figured I'd ask in the hope that there's a better way.
My understanding is that once I add the Toggle button, the Comp component is cleared from the process and the hooks are rendered out of order from what they expect. I'm trying to change my program over to a useReducer so it's easier to pass state back up the tree 5 levels, then down a different path. The problem is I'm not sure how I'm supposed to do this when I have to mix props and functional calls together, and am stuck either randomly trying different things, or trying to shoehorn my program into a pattern I see in a tutorial. I'm sure I'll get it this way eventually, but would really appreciate any pointers, thanks!
When running a react app using the typescript template, I need to restart the server between edits to see my changes, is this normal? When using a default js template updates are reflected immediately.
I created the app using npx create-react-app my-app --template typescript
The hook is called at the beginning of the function setting the state to a default of empty. Isn't the function called each time the component needs to be re-rendered? Wouldn't this reset the state to empty each time? I don't see how this works.
I have a list of items, people can add or delete items in it via PUT or DELETE requests. The list of items is shared with all my other components. It works fine!
I want to put it in my portfolio. But!I don't want users to change my database but I want to showcase that it works. It would suck to have a random person visit the site and then delete everything. Any workarounds for this? I disabled the add/delete items feature for now!
I have a couple of components that are using data from global state to calculate display values on render. They use the same core calculated values. My goal has been to avoid performing the same calculation separately in each component.
My current solution is to create a parent component that does the calculation, then passes the values to the children in props. Works fine since the two components are adjacent in the DOM. But what if they weren't, and it wasn't practical to use this approach?
How can two separate components share that sort of data?
How widely used is grpahql in the industry? I learned the concepts of it and I am aware of the benefits over REST but I feel like most sites can be done via REST!
But at the same time, you could argue every site can be made with GraphQL, it's just that the boiler plate code for graphql seems to be much more than React + Redux!
I need to rapidly make the frontend for a heart rate monitoring device. A team member is building the device, another person is working on the backend to communicate to the device and send me states, and I need to write the frontend that updates the states and can handle touch events. I plan to use React w/ Redux in vscode.
I have extensive experience with programming (data structures), systems programming, and machine/deep learning research (C, Java, Python...etc), yet I have not worked with JavaScript.
Any tutorials, courses, or websites I should go through will be greatly appreciated.
The previous responders answer is excellent. These are called generics if you want more detail on when and where to use them this is a great explanation of their purpose https://www.youtube.com/watch?v=nViEqpgwxHE&t=297s
Hi, I am trying to work on a Kanban Board feature on a website using the Dragula API. The problem is that I have never used an API before and this is my first React Project, so I have lots of trouble understanding the documentation. Every example for Dragula React-JS that I have looked at feels like Martian. How do I go about understanding how I should work this API?
I'm trying to update a field in State only when two other fields are not null. The field to be updated should simply calculate the difference between the two other fields. The updating works fine but the math is WAY off.
For example:water1=20water2=25consumption=-18 (<-- what!? This should simply be 5)
My code inside handleChange is:
handleChange(event)
{const { name, value } = event.target
this.setState({ [name]: value })
this.props.callBackFromApp( event )
if (this.state.water1 && this.state.water2) {
this.setState({ waterConsumption: (parseInt(this.state.water2) -
parseInt(this.state.water1)) }) } }
I've tried to use the parseInt to make sure that it's not interpreting string values instead. But it seems I'm not completely successful with that.
Is it possible to add a whole bunch of instances of a react UI component to an html page?
To give a simple example, there's a "ul" with 25 "li" elements inside it, can I target the li elements and replace every one with a react implementation of a list item that does cool stuff with the li content?
All the examples online show a single root element with a react app mounted to it, but could I, for example, create my own implementation of a "button" element and replace every html button on a page with it?
Hi! I am developing a web application in which the user has to complete steps to finish a task. The steps are:
Wait for the user to scan an image. To simplify things, assume it arrives via websockets or something like that.
The scanned image is displayed and user confirms or rejects it. If she confirms, she goes to the next step.
Screen shows the image and a form and user has to complete the form.
Every step has to be completed to finish the process and always in the given order.
My question is, how would you handle the step state and the data the steps need?
I was thinking of using react router and then give every step a page like /step1, /step2, etc. Then every time a step is finished I would call window.location. The problem is I'm not sure how would I give the next step the data it needs, like the scanned image in step 2).
Also, I'm not familiar with hooks, redux and context, maybe these can help me in any way?
I'm pretty close to 100% noob on ReactJS, so my question may be pretty simple to answer.
I have two text fields, firstName and lastName, which I need to use logic on as either one changes. For example, if someone is typing into the firstName field, I have an onChange event that is triggered calling a method in the same component. I can access the value of the calling event item using event.target.value but I will also need the value from lastName text box as well.
What is the best way to get the additional textbox info into my method? Use document.getElementById('lastName') as a parameter in an error function calling the method in onChange? Or use document.getElementById('lastName') inside the method in my logic? Or is there a better way that I am not aware?
I want to use the best method possible, so I'm using the proper techniques going forward.
hello I am trying to create an application where users only see profiles with whom they match. however, I have no idea how best to approach this matching. Do you have any tips or tutorials explaining this?
I'm making a sudoku-ish game, where the player has to guess what numbers are in the grid based on hints they receive about the numbers' mathematical relationships. So far so good, but now I've hit a snag. Below is the structure for the <Hints /> component
displayHints = () => {
let hints = this.props.game.getHints();
console.log(hints); //this outputs new hints to the console each time it gets called
return hints.map(hint => ( <p className="hints">{hint}</p> ));
}
generateNewHint = () => {
//let hint = this.props.game.newHint(this.props.difficulty);
let hint = this.props.game.addHint();
this.props.game.setHint(hint);
this.displayHints();
}
render() {
return(
<div className="hint-container">
<body className="hint-body">
<div className="hint-list">
{this.generateNewHint()}
{this.displayHints()}
</div>
<div className="spacer"></div>
<div>
<button className="hint-btn" onClick={this.generateNewHint}>Get another Hint</button>
</div>
</body>
</div>
);
}
this.props.game is a reference to my new Game() in my App.js, which I have here:
This new Game() refers to my Game.js file which holds all the game's logic: the masterValues, userInputs, and the hints. The methods inside of Game.js, setHint() and getHints(), work perfectly for setting and getting new hints. Everything works, except I can't get my new hints to render. In my Hints component's render() function, I'm calling this.displayHints() to list the available hints, which works when the first one gets generated at the beginning of the game. After the user clicks the button, however, new hints are not being displayed even though I am calling the function again inside this.generateNewHint(). The console.log() is working and listing the appropriate hints. That's problem 1.
To solve this problem: I have tried switching .map and .forEach, I have tried setting hints to the <Hints /> state, and I have tried setting hints to the App.js state object. Neither .map nor .forEach works to render the new hints, just the first one. The latter two solutions didn't refresh the component when setState was called, which resulted in the new hints not being rendered.
Problem 2 is that my hints say "The number in [object Object] plus the number in [object Object] equals 0." It should be getting the key of the key/value pair for each individual number. This is should be something like A3, B1, C4, D2, etc. This corresponds to a square on the board at row Letter and column Number. The hints should read: "The number in A3 plus the number in C1 equals (sum of the two numbers)". The object that gets passed in looks like this: {A1: 24} The key is dynamically set and the value is randomly generated and then assigned.
So my quesitons are: 1. How can I get my list of hints to be rendered dynamically? What's the best way to do it? 2. How can I access the key and the value in my hint objects separately?
I know that react is all about components and building them up. But I am stuck on how you lay them all out to fit your design on paper.
For example, say I want to make an Outlook clone with a tree view on the left and on the right side of the page, have it split horizontally. The top half would be a list of emails and the bottom half would be the email detail. Then at the top of the page, have tabs to flip between inbox, sent items, calendar, etc. When you click on a different tab it could totally change the contents of the main page.
In my mind I can see how to make all the individual components that do each thing, but I don't know how you would put them all together? How would you guys go about doing this? Is there a package you pull in?
Or do do you use a grid system? But then if its a grid system, how would you make the tree view panel resizable for example? (or is that advanced)
The tabs is a great use case for a UI library. The major ones, like semantic UI, definitely support them. I would do that rather than roll my own tabs (ugh).
To have it split horizontally - that sounds like 'width: 30%' for one div and 'width: 70%' for the other, with something like 'display:inline-block' (or whatever it is, please look that part up).
And I would use media-query to send different layouts to desktop and mobile.
I am trying to create a registration page. I am already able to write data to Firebase database. However, I get stuck when I want to upload the profile picture to firebase and save the reference in Profile on the database. Does anyone have a good tutorial or tips for this?
So having this weird problem where my react app isn't showing anything to the browser and I'm not sure why it was working fine before I'm working through a Bootcamp and learning react and im completing lost on how to fix it
I've recently been tasked with providing a new React based UI to an existing WebGL application (currently using Knockout) and am having some trouble figuring out how to handle sharing state between the UI and the WebGL application. The application must be able to trigger UI updates and vice versa.
So far I've tried to use the useEffect hook, which lets the UI update the application, but it requires diffing against previous state to detect when things have actually changed. I also have no idea how to get the application to update the UI without using an EventEmitter to trigger a full ReactDOM.render call.
Has anyone else had to deal with this sort of situation and if so how did you manage it? Are there any established patterns for dealing with it?
Then, use the second element of the returned tuple (api in the readme) to access your state setter methods of the store when settings get changed in the WebGL app (api.getState().mySetterFunction()).
Then, use api.subscribe() to apply changes from the store to the WebGL app.
This way, changes only flow from the store down to react and WebGL.
Hi there, I'm new to React and am trying to create a workout tracker web application.
So far, I decided that when the app first starts, there will be a homepage that has 3 buttons: Create Workout, Select Workout, Stats. These options were created via the common component, WorkoutOptions.
Now, my goal is to be able to click select workout, and have a new Container component show up to replace the existing 3 buttons, essentially moving the user to the "next" page.
However, I'm unsure of how to do this.
In my head I'm thinking that if the App Component detects that selectWorkout is clicked (via event listener), it will render <Container/> and unrender(??) the Option Cards
However, that clearly doesn't sound right so pointers would be much appreciated
Use the useState() hook in App to store the current selection. When there is none, show WorkoutOptions. App will pass a "selectOption()" prop to WorkoutOptions that is called with the value chosen in each button's onClick handler. The state setter returned by the useState hook will suffice in this case (as a learning experience). When you get your feet planted on solid React ground, look into react-router, which replaces the single piece of state in App with an app-wide piece of state stored as the browser's url. Using a router isn't necessary but makes life easier both as a developer and user when other features emerge.
Hey guys - I was able to build a small application that takes input, uses the input to call an api, and displays the results from the api. Let’s call this the platform.
How do I go about making another page, let’s say a landing page, where I can login and signup before being able to access the platform?
I have only used react for this application so far, nothing server side yet.
If you want to make a login page, youll have to do some server side work. Outside of sending the username and password to your server, the frontend should avoid any log in logic to avoid gaping vulnerabilities
Noobie here with a few questions, the first one is as simple as it gets and I thought I knew the answer to it. In the following code I expected to only log to the console once as the state is set before rendering and therefore a second render should not happen because the state never changes but rendered is logged twice.
The second question I have no code example for but the issue I have is using the response from one http call as a part of another http call that immediately follows the first. I'm using async/await and putting the response in state but as setting state is async the second call starts using an undefined value. What's the best way to handle this? Thanks in advance for any help.
React is allowed to render components extra times if it chooses to. In development with StrictMode all components are always rendered twice.
The second question I have no code example for but the issue I have is using the response from one http call as a part of another http call that immediately follows the first. I'm using async/await and putting the response in state but as setting state is async the second call starts using an undefined value. What's the best way to handle this? Thanks in advance for any help.
The async action part should happen in a useEffect call. The second fetch is for a second piece of state, so it should also happen in a second async call. Something like the following:
function App({ id }) {
const [profile, setProfile] = useState(null);
useEffect(() => {
setProfile(null);
let stillCurrent = true; // tracks when unmounts/changes
fetchProfile(id).then(result => {
if (stillCurrent) {
setProfile(result);
}
})
return () => {
// cleanup function
stillCurrent = false;
}
}, [id]);
const [comments, setComments] = useState(null);
useEffect(() => {
setComments(null);
if (profile === null) {
return; // nothing to do yet
}
let stillCurrent = true; // tracks when unmounts/changes
fetchComments(profile.commentIds).then(result => {
if (stillCurrent) {
setComments(result);
}
})
return () => {
// cleanup function
stillCurrent = false;
}
}, [profile]);
}
Notice that I included some cleanup stuff, which you need to make your components robust to race conditions. For this kind of thing, a custom hook is helpful, so that your components can remain more "focused" on what they're supposed to be showing. E.g. something like
This isn't really complete (for example, no error handling) but it gives a good idea of how you can make this look. There are React hook libraries already out there for doing this sort of thing, but I can't vouch for any in particular.
Both issues you’re experiencing are called “side-effects”. Basically for your first problem you have to wrap console.log on a useEffect hook, the second one could be solved in the same way but it gets cumbersome to say the least. When you’re dealing with several dependent side-effects, a good way to solve this is by using sagas, or if you just keep all the async calls within a scope and save the state later and avoid the race conditions all-together, just my 2 cents
I am working on a hobby project that has some very CPU intensive reducers in redux. I’d like to explore running those reducers in a web worker.
It looks like I could extract the reducer code to a module and use worker-loader + comlink + redux-thunk to do the work asynchronously.
Am I thinking about this correctly? This is a bit outside my comfort zone, appreciate any advice!
It may be simpler to not use redux and switch to context when using webworkers, but the redux dev tools and packages like redux-persist are really nice to have.
What's the preferred way to fetch data when a user navigates via React Router?
My best assessment at the moment is that if you have a standalone page (ie a user can navigate directly to it), it's best to make it a class so that you can check the state and fetch data if the route parameters are updated, but I wonder if I am missing something obvious.
FWIW, I'm using Redux with React Router. Thanks in advance.
You have StrictMode enabled. In development, all components render twice for each update, to help catch bugs related to side effects in render (which you should avoid).
Im new to react - ive built a few static page websites (2-3 pages) looking how I can integrate with databases and expand my knowledge and learn what react can offer for my development is there any quick resources I can take a look at
Hey, to integrate with a database you will be entering to the world of "full stack development" (that is what you should be looking for).
A "full stack developer" is someone capable of doing just what do you want to do: create a website that is connected to a database.
If you search about this term, you'll be stressed out about how many technologies you need to learn to do that :( because it is not as simple as running a line of code. Here is a small intro: https://academind.com/learn/react/connect-to-database/
I am working with the Spotify APIs and authentication and am a bit frustrated by the relatively short expiration time of the access token.
I tried using jwt-decode to check the expiration date/time, but I get an error because the Spotify access token uses _ rather than "." (I think; I get an error anyway whenever I try to decide the Spotify token)
Are there other libraries out there that people like for deciding JWTs?
My other thought is simply to refresh the access token with each Spotify call, but that seems excessive and I worry it wound affect performance.
Maybe you already know it, but you cant refresh the token from the client. My solution for this is a nodejs server that handles the tokens and each request to the Spotify API. Take a look for inspiration. Its not perfect and under development.
Hello, In material UI documentation I found something that Ive never seen before. Can someone explain to me what this is ?.https://prnt.sc/sdcyc1. And If i turn it to a regular ES6 arrow function, i get this error https://prnt.sc/sdczmu . What is exactly happening here ?
As I understand it, react native is for phone app development and react redux is basically the express.js to react's node.js? ie. Simplifies and adds useful functions.
I haven't used react for a while, and rather than relearning it (a lot seems to have changes), I'm thinking of diving straight into learning redux - is this advisable?
I've been creating a Todoist clone, but can't seem to properly implement inline tagging. I know how to identify and store the tag using RegEx, but can't figure out how to format the text in real time after the user has prefaced a word with a #.
From my research, it seems that this isn't possible using a standard input (e.g. textarea) and instead maybe need to use a div with contenteditable? Would Slatejs or another rich text editor framework help me here? They all seem too complex for my needs.
What is the best way to fetch data from a graphql endpoint on the client? I've tried setting up Apollo (love the websocket support) but it's extremely difficult to get working.
I'm using NextJS, so it's important that the data fetching is purely performed on the client. I had problems where I was initializing the client during server-side rendering, and I wasn't sure how to avoid that.
New to react, but I have a project I'm working on. I have a webserver (apache) on my raspberry Pi, and a few Pi Zeros to act as web browsers locally. I am setting up a pi as a Nas server for my photos. I want to use react.js to have the pi zeros browse to the apache server and see a sideshow of the images. I want to be able to filter the images by date, rating and tag. Would I be better of loading those images into a db and have the browsers pull that data or what? I want to do the filtering from one device yet show on each device. Thanks for any help
My friends wants me to make a simple blog for her. Mostly just a static web page along with functionality for making comments and such, nothing else. I mean she could just simply use wordpress or something but I figured I could just make it and put in my portfolio.
All other front-end type of projects I have done before I have done using the create-react-app, but I heard this has terrible SEO. What would be a better alternative ? I figured this would be a good time to checkout GatsbyJS or NextJS or something along those lines and step away from the create-react-app for a bit. Any recommendations ?
Hi there, I've been pretty confused as to how to use States to pass information from the child back to the parent and would really appreciate some guidance!
Currently, I'm trying to create a Workout app where the homepage contains two options: 1.Select Workout 2.Create Workout
I want to make it possible for one to click on "Select Workout" and go to a "new page" with a different container Component.
However, I'm confused by which component should own the onclick event listener.
Currently, my Component Hierarchy is as so:
App.js
Homepage
OptionButton (1 for Select Workout, 1 for Create Workout)
Select Workout Page
I think that the component OptionButton should have an event listener that detects when a button is clicked. But the problem is, there are 2 items that use the component OptionButton (Select Workout and Create Workout), how would the program know which of the two buttons was clicked and how would it store that info to be passed back to the parent component?
Currently, they are rendered as two different objects under Homepage.
return( <div className='flex-container'> <OptionButton id = {1} info= "Create Workout"/> <OptionButton id = {2} info = "Select Workout"/> </div>
I have a simple react application kind of like a paint application. I’m wanting to add a feature where I can undo and redo changes made, would I be best to add something like redux so I can keep a track of history changes ?
The "something like redux" is anything command/response based. I would not hesitate to use redux because there is lots written on the topic of undo/redo around that lib in particular. But just getting to the place where you dispatch commands to central bus is what you want to start with.
I'm having a heck of a time trying to understand how to use this Higher Order Component supplied to me from a tutorial.
My understanding is: Without this HOC, I would have to put Authentication logic into every component on my site. So what this HOC does is extract that logic, store it, and "wrap" its contained component, injecting (somehow) Authentication logic in the process.
meaning, the HOC, called withAuthentication, should at least pass its state(?) down to the component it is wrapping. I believe there is something else going on with the Context API that I need explained too...
So I see the following: in componentDidMount(), there is some code that runs onAuthStateChanged "sets an observer" (see link below) that essentially gets the User object from Firebase Auth. Then that authUser object is stored under authUser in component state. And hypothetically I can do something with that stored User object, only, I don't know how to access it in the wrapped component?
all my Google attempts returned StackOverflow links about passing state from child to wrapper, not wrapper to child.
Next in componentWillUnmount() there's "this.listener()" which I do not get. The tutorial said it was to prevent memory leaks.
Lastly there is something going on with the COntext API and this HOC... The HOC is passing its component into the AuthUserContext.Provider. The question is what does that do for the wrapped component? Can I access the value passed to "value" in the Provider somehow?
My goal is to do something like:
import React, { Component } from 'react';
import { withAuthentication, AuthUserContext } from "../Session/"
import { withFirebase } from '../Firebase';
class InboxPage extends Component {
componentDidMount() {
// goal: retrieve user's chatrooms from database and populate the render() method with them
const username = // how to get the username? I'm sure it can be done if I can access the wrapper's state
// connect to the database
// retrieve messages from database
// display retrieved messages to user
}
render() {
return (
<div>
<h1>Welcome to the Inbox.</h1>
<p>Here's your messages: {}.</p>
</div >
)
}
}
export default withAuthentication(withFirebase(InboxPage));
So basically I am trying to figure out how to get the name of the authenticated user in the InboxPage component. But more than that, I want to understand how HOCs and the Context API works: "How do I pass data between HOCs and their wrapped component?" "How can I get that 'this.state.authUser' I see being passed into the Context.Provider?"
Anyone experienced with combining React and Firebase? Please comment if you're available for between 2 and 5 hours a week for the next month or so. I'd like help on a project. Will pay (a little)
edit: I can do what I want when it's just Firebase and JavaScript, but when I throw React into the mix I get strange and/or unpleasant results. Send help
I applied for a software engineering role at a large bank, and their tech team decided that I would be a better fit for a full-stack role, considering my experience.
I'm pretty sure they're going to ask me a bunch of React questions, and while I've worked with Node/Express in the past, I've never used React. I've got two days until the interview.
Am I fooling myself in thinking that I could learn enough React to pass a basic interview?
I'm trying to build a simple blog using test data. Trying to figure out why reloading the page breaks my component. I'm fetching all the data in the App component and passing these down via the Routes. It works great if I start at root, but if I navigate to a detail page and reload, it breaks and returns " TypeError: can't access property "userId", selPost is undefined ".
I think it might have to do with how I'm fetching the data, but I'm not sure about that. Any help is much appreciated.
I am a full stack c# dev and doing web apps where the frontend is usually just html css jquery.
I recently jumped in and completed the React course on Scrimba, which I thought was great intro into React, especially as you pause and alter the code to see what happens.
I am thinking it might be a good idea to do another course but not sure which one to go for. The full react course on scrimba or the one from Tyler McGinnis. Both are paid courses so I'm not sure which would be better for me and the background I have around coding in general already.
Or should I really be doing another course at all now that I have the basic. I can just start building things and learn as I go.
Depends how you learn. I learn by doing, so attempting to build something I am actually interested in is the best way, then I can pair that with referring to the docs.
How do companies handle updating their react code in production? I see articles suggesting to use "service-workers" and use the "skipWaiting" feature with the notification "Update Available" with an update button. But I've never really seen the idea of "updating" a web app anywhere. So how do they do it?
When do you use componentWillMount()? I'm reading that it gets called right after the constructor and before render() so why can't you just put whatever is inside there in the constructor instead?
I'm having trouble on an app that allows users to store & view 'benchmarks'.
I got to the point where a user can upload & view these 'benchmarks' successfully, however I'm trying to implement a search function to filter the viewable benchmarks. The way I thought this would work is that I would pass the list of 'benchmarks' to the child component that is doing the rendering and set a 'filtered' state within that component where once the user inputs anything into the search bar, this new 'filtered' state would only have the 'benchmarks' that match up with the inputted values and then of course render that new list...
Currently I'm running into an error where my loadData function that actually maps everything out is breaking as the list is 'undefined' - also tried to set a condition within the render so if the filtered list is not defined it would just render the original list anyway (this.props) however it still breaks but it will work if I hard code "this.props" as the value to map over which is the real confusing part...
Sorry for the wall of text! I'll post the code now - appreciate any help.
Can someone help me? I try to show te username and picture in the navbar after the user logged in but i cant seem to retrieve the user details i saved in firestore. I try to do this with the useEffect hook but it loads before the authenticated user is loaded from the context. Which returns a null error
I have an interview test to prepare for and they are wanting me to hook a node api into the front end react - can anyone suggest some good approaches to take with this any help will be amazing :)
So I'm watching the Scrimba tutorial for React (created 2 years ago) and the guy is using React version 16.3 and talking about how "hooks" are the new thing and he believes they'll make class components unnecessary. Did this end up happening?
I was just getting the hang of class components too...
I'm a bit confused on how to use axios in React with express framework for node.js.
My proxy for express is on port 5000;
This would work if I'm on localhost:3000:
In React
___
axios.get("/").then( (resp)=> console.log(resp));
In Express
__
app.get("/", cors(), (req, res, next) => {
//Data would be fetched, and GET would appear in my terminal.
console.log("GET");
});
But when I host the actual website, GET in express doesn't work.
In React
___
axios.get("https://music-json-server.now.sh/db.json/ ").then( (resp)=> console.log(resp));
In Express
___
app.get("/", cors(), (req, res, next) => {
//Data would be fetched, but GET would not appear in my terminal.
console.log("GET");
});
Hello, does anyone have any tip on some learning react guide that is audio only? Like a podcast. I'd like to listen to something for example at the subway. I want them to talk about how react works and the code and not random stuff all around the subject.
I know it's probably not the best way to learn but it's still better than nothing!
In your routes page, always try to order ir from most to less specific. In this case, always start with the /platform, /about and finally with the Home. Event though it should pass, because of the exact. Try it that way and see if it works.
First off, I am not a novice programmer but I have absolutely zero experience when it comes to website development. I want to build a react website to learn some new skills in this area.
A little description: Lets say I want to build a website where the user can type in some data, and then when he is done he can download the data as an .xml file or something similiar (just to save it locally). After downloading the file the user should be able to upload the file again and reload the data in the application. Basically I want to make an online data manipulation tool without a database.
But I have a few questions on how I should approach this. First off, does the user really need to upload the xml file to the server or is there a way to just load the data another way since technically the javascript is running on the local webbrowser? I don't really need the xml file saved on my server.
All the things I found with google are more into the direction of how to generally upload files but not how I can work with them. Even if I would use this approach, how would this work with multiple users? Would I need to build a complete serverside application (with node.js or similiar) to handle the incoming xml files?
If somebody has a general point of direction for me which keywords I could google, or maybe the names of a few packages or a tutorial that might help me, that would be greatly appreciated.
In my component, I have a variable called selectedExam which is passed in as a prop. I am then trying to show a row in a table for each section in the selected exam.
var selectedExam = props.selectedExam
var examSection = examList.exams[selectedExam].sections
everything compiles and a table row is shown, and section.name shows the exam name (i.e. "First Exam" or "Second Exam"). Once I add ".sections" to try and go down one level further, I get this error: TypeError: Cannot read property 'map' of undefined.
I am confused, what variable are you adding '.sections' to? If you are adding it to examSection it would not exist.
The TypeError is suggesting that whatever you are trying to access is undefined, it might be that you are passing down a prop that is not actually defined.
Does anyone know a fairly straightforward way to create a touchenter & touchleave event in react? onTouchMove fires constantly and I'm not sure how to parse that data to just fire when the touch enters a specific element. I'm using typescript but feel free to respond using regular js.
const touchEnter = (e: React.TouchEvent) => {
// some condition on element?
// execute
}
Also if anyone knows why they removed touchenter and touchleave from the spec I would love to know the reasoning behind it. Seems like it just complicated things for no real benefit..
I have a simple comment system built on my Gatsby site, and I want to implement something like Wordpress' comment-reply.js.
Goal: a reader can click "Reply" on any comment, and the comment form will 'jump' under the comment (e.g. <li id="commentid-8584">). If they click "cancel reply", it will jump back to where it was.
What's the simplest way to move an element onClick like this and then back again if the user cancels?
Hi I’m currently working through Tyler Mcginnis’s React class and was going to do his React Hooks class immediately after. When I’m done, I was going to start my own project. Would these two courses be enough to get me started or should I learn other tools like Redux before?
I suggest you start building something already, and add new features as you learn more. When your project grows, then you will feel need to improve your codebase, and then Redux can come as a solution. What I'm saying is, feel the pain of managing app state across different components first and then try different solutions for it. That will also make your learning process way more efficient.
Better to get a firm grasp on react and how it handles states natively before using redux.
Once you do that and “struggle” with managing your states across components and pages, things like The context api and state managers like Redux and Mobx will make more sense.
when a user is logged in I would like to display in the navigation a small version of profile picture and name of the user. Does anyone have any tips on how to do this best? I use React hooks and firebase. The user is stored in firestore database.
Couple of questions. I've made a very basic website (just some hyperlinks in the footer) because I'm new. and I get these two errors whenever I start my website:
Uncaught SyntaxError: Identifier 'getUILanguage' has already been declared - polyfill.js:1
Uncaught SyntaxError: Identifier 'pairs' has already been declared
These errors go away when I disable adblock (even though there are no ads on my site). Could someone explain why this happens? Thanks!
Hi, I'm learning React hooks after just finishing regular React and I am confused why we have to use a function inside of useState when setting the state based on the previous state. For example, in a todo list we use
setTodos((todos)=>todos.concat(todo))
I tried using
setTodos(todos.concat(todo))
and that worked just as well. Is there something I am missing on why we use the first method instead of the second?
then it will only include todo2 and not todo1, since the second update will entirely overwrite the first one.
But if you're only dispatching one change at a time, there's no difference.
There can also be some "ergonomic" differences - in some cases (especially when calling useEffect/useMemo/useCallback, which care about object identity) passing the "current" value of state might make things "change too often", and the function-update form means you don't have to do that.
Hi, im creating a react shared component library and I'm not sure how to handle CSS.
Currently when I use the component library in a project I just load all the CSS into that project but it is possible to break up the CSS per component so I'm loading the CSS with the component?
For example instead of doing:
import {allStyles.scss} from "@repo/shared"
Would I do:
import {CommonGrid} from "@repo/shared"
And have that import the styling the CommonGrid needs?
I'm trying to make my dialogs usable and was thinking about giving them a promise-based API - using a hook that looks like this (sandbox):
function useDialog() {
// store the resolve function to notify the caller when the dialog was hidden
const [resolve, setResolve] = React.useState(null);
async function show() {
// eslint-disable-next-line no-throw-literal
if (resolve !== null) throw "show called while dialog is visible";
return new Promise(resolve => {
// this is a little strange - pack the resolve function into an array,
// so that React won't try to do a functional setter call.
setResolve([resolve]);
});
}
function hide(result) {
// eslint-disable-next-line no-throw-literal
if (resolve === null) throw "hide called while dialog is not visible";
const [realResolve] = resolve;
// give the result to the caller
realResolve(result);
setResolve(null);
}
function bindDlg() {
return {
visible: !!resolve,
onSubmit: () => hide(true),
onCancel: () => hide(false),
};
}
// return everything necessary to display the dialog
return { show, bindDlg };
}
Usage looks like this:
const dialog = useDialog();
<div>
<button
onClick={async () => {
const result = await dialog.show();
// do something with the result
}}
>
open
</button>
</div>
<Dlg {...dialog.bindDlg()} />
I have already identified some issues here, such as multipe show() calls before a re-render not triggering an error because the if (resolve !== null) condition won't identify the change; same for multiple hide() calls. However, when I would change this to use functional state updates, I think I'm not even able to throw an exception to my caller, correct? I'm not really too concerned about that, because those are assertions anyway and shouldn't be able to happen, but then there's also the side effect of resolving the promise in hide. Doing that in a state updater is also not clean, no?
But the main issue is in the onClick handler: after the await point, the async function will still have captured old state from when the click event happened, so when processing the result I won't be able to access any state without keeping in mind it's probably stale.
Being able to say result = await dialog.show() seems so desirable, but it also looks like using async functions at all is a huge footgun with how capturing of state works. Is there any way to achieve this API safely?
I'm working with a shared component library using Yarn Workspaces. Am I supposed to commit the /dist folder from my comment library or should I need a way to have that generated when importing it into my application?
I forgot to commit it so when my team pulled master they got a reference error when trying to use something in /dist
As a general rule you never commit anything from dist or build folders as every other developer in your team can run the script to build it themselves. You can automate it, so build is triggered together with yarn install or yarn start so then everybody running your app locally will have to build your dependencies first.
Different rule applies when you publish your project as npm package, then you might include dist folder as a ready to use dependency.
`useRef()` accepts as a parameter a so-called initial value, yet when used on a <input /> the value doesn't show up.
const inputEl = useRef("This should be visible but it's not")
return <input ref={inputEl} type="text" />
The input box just shows up empty.
I wanted to avoid dealing with the `useState()` , `value={state}`, `onChange()` boilerplate for a simple input element, and thought I could use refs, but seems that that's not possible. Why doesn't the input box display the initial value specified in `useRef()`?
I'm working on an app that requires oauth authentication to Instagram. I'm able to complete the authentication without issue but I'm struggling with keeping state after being redirected to the IG login screen.
I built a component that handles the login, callback, etc, that I'd like to be able to reuse across my app in different places. After login is successful I'd like to make sure I'm still on the page where I initiated the login (eg. user profile page).
When IG authenticates I need to redirect to the IG login page which I in turn provide a callback url to. Initially, I was able to work around it by popping out a window and using local storage but I don't want to use a window when on mobile. For this I have a route the directs to my component, and once completed I can use history.push to get back to the profile page, but I can't figure out how to make the push to the calling page dynamic. Is there a better approach to this? Will context API survive a redirect?
I'm making attempts to get out of tutorial hell and create a very basic game for myself.
I've mocked out the design in Figma to have 3 different screens, with each showing specific components for that screen or page:
User input in order to get to next screen
Game in session
Summary screen showing score
I'm pretty new to this but in my mind I'm thinking I need to use React-router as there are different pages. So how do I pass my state around the different routes? Is this a situation to use Redux? Is that what is still commonly used? Additionally I'll also be storing data from state into my localStorage when the game is finished and then eventually into a database but just taking baby steps.
I have this very basic function to call a function in another file, though what happens is that it constantly tried to call this function and thus keeps on loading. How do I make it so it only calls this function once once I load the page?
I would like to have one image as the footer of my website with text overlayed on top of it in different sections.
This is my image and I would like words in each of those blocks. Is there a way to do this on one fell swoop/component or would I need to divide the image into 6 different components and have the footer render all 6 side-by-side? Thanks!
Create something of your own from scratch first or if you have created something with just JavaScript earlier turn that into react based website, add functionality to it if you can. Following a tutorial is not a test of your skill ability to make things using what you learnt is.
CRA - Least effort to get it up and running, but not a good choice if SEO is important. For larger apps slower initial page load, but fast after that.
Gatsby - Really fast and excellent SEO. Best choice for blogs, landing page apps. Not the best option if your site has a lot of dynamic data. More configuration compared to CRA. Has good headless CMS starter kits/plugins.
Next.js - Uses server side rendering , scales well with large apps.
Depending on your level of experience, you can start by going through the Gatsby official tutorial.
Once you feel that you grasp the main concepts, pick a small project to build. While building that you will have to read the docs & do plenty of googling. That's the best way to learn.
It depends what is your use case? Are you building a personal blog or a serious web application?
For static websites Next.js is a good candidate. Gatsby is also very popular and relatively easy to use. I hear that Eleventy https://www.11ty.dev/ is becoming popular recently.
For big web apps, my experience is that you use express or other node server to server-side render your app on demand. It uses ReactDOMServer.renderToString().
For starters, functions are values and there is nothing wrong using them in context. I'm not necessarily advising to do so here, just pointing out the legitimacy of the suggestion. Just to clarify, TopBar is ignorant of what and how to save, but is the UI for invoking a ConfigPage save because a config page lacks the UI?
6
u/badboyzpwns May 11 '20
about hooks, why do we use const when declaring the variable? especially if we are planning to change it later? For example,
3
u/[deleted] May 01 '20
I'm currently learning React through https://fullstackopen.com/en (nice open university course from finland for anyone interested)
Looking for help with custom hooks. So I have a custom hook which handles a forms state like so:
importing useField into the app to be used as follows:
the spread operator {...content} throws a warning: Invalid value for prop `reset` on <input> tag.
The question is how can I maintain use of the spread operator while also fixing this problem?
I feel like it is an easy fix that I am just not seeing. If you wish to see the problem in full and most likely explained better its bottom of this page https://fullstackopen.com/en/part7/custom_hooks question 7.6
Thanks in advance all
3
u/GhostofBlackSanta May 28 '20
How does rerendering work when setting multiple states? For example when I have a button with an onClick that calls a function that has multiple setState hooks, does it rerender for each setState or does it go through everything and then rerender all at once?
2
u/badboyzpwns Apr 30 '20
why do you have to use a class for redux-form? I tried building it with a functional component and it re-renders/makes me unfocus the input. These 2 examples below are the exact same code! but I demonstrated both with a class and a functional component.
Class:
Functional component
2
u/dlrwtllktgrtt May 04 '20
I've deployed a React app talking to a Firebase Firestore DB using Amazon's Amplify service.
My Firebase API keys are defined in the AWS console as environment variables.
My question is: Is this a secure way of doing this? or are my Firestore API keys and other secrets accessible for someone who chooses to go through the compiled files in a browser?
I found this in the React documentation that has me confused:
Edited for clarity.
2
u/badboyzpwns May 12 '20 edited May 12 '20
Problem is, I have to click the button twice in order for <Link> to be triggered.
Putting <Link> outside <button> makes the anchor tag/<Link> not inherit the button's width/height.
Any workaround for this? Is there a react property that i could use or is this more of a css thing?
2
u/badboyzpwns May 15 '20
I'm planning to intern as a junior dev! Is it valuable to learn Testing such as using redux-saga, Jest, etc? (I don't see any job postings specifying that I need to do unit tests, etc) Or is this more of valuable asset for experienced senior devs?
1
u/NickEmpetvee May 01 '20 edited May 01 '20
React 16.13.1 (via create-react-app that executed a few days ago)
Implementing a file upload prototype and using a tutorial. The below code yields a
POSThttp://localhost:8000/upload/image404(Not Found) as a result of theawait fetch. I've created a folder '/upload/image' under '/src' and '/public' with the same result. Also tried changing the fetch target location to '/' with no love. No special configurations to node.Also tried with AXIOS that yields
Failed to load resource: the server responded with a status of 404 (Not Found)Huston we have problem...: Error: Request failed with status code 404at createError (createError.js:16)at settle (settle.js:17)at XMLHttpRequest.handleLoad (xhr.js:61)Any ideas?
1
u/Jorick_DC May 01 '20 edited May 01 '20
Hello,
I have a quick question. I was following the tutorial below to build a multi step form with react hooks. but I don't understand why he uses <div> instead of <form>. and how you can send the data with onSubmit = (event) => {}. Thank you for your time.
I think I will need to use the effect hook to acces the api point to write the data to my database.
the tutorial: https://medium.com/javascript-in-plain-english/how-to-create-a-multi-step-form-with-react-hooks-53a85efdff62
1
u/Amerzel May 02 '20
If you were starting a new app and we’re using redux for state management would you use react-redux or @redux/toolkit?
1
u/[deleted] May 02 '20
Hi, I have a question about this counter component.
I click the button and the value of the button increments. Nice! But after I call
setCounter(counter + 1); and callconsole.log("counter", counter);` on the next line, the output is always one value behind. How come? Is there a way to fix this? Thanks.App.js
Button.js
1
u/badboyzpwns May 02 '20
newbie question about redux. If I only wanted to use ComponentDidMount() and call something once. Should I use a class or a react hook?
For example:
vs
I tend not to use setStreams() so it may be redundant. I'm thinking classes are more suitable for this?
1
u/ortz3 May 02 '20
Is creating a key to render a child component a good design practice. For example I want to send the userId to a child component, but the child component is loading before the userId gets set. This is what I currently have and am wondering if this https://stackoverflow.com/questions/56640380/how-can-i-make-sure-a-react-parent-component-loads-data-before-its-child-compone is good design practice
1
u/badboyzpwns May 05 '20
I've read that it can be bad for performance when you have deeply nested components and you create an anonymous function in an element. For example,
Because of the anonymous function, React will re-render every single element in the component because it thinks that the component changed.
How do you guys counter-act this? Does doing
a better alternative?
1
u/floghdraki May 06 '20
If I pass function to parent component and call it (without using imperative handle) why can't it access current state of the child component? What is its context? Could someone reference me to the concepts that explain this behavior?
1
u/089-083 May 07 '20
Guys, how does one go about building a website + platform like this app: Flowalgo.com
1
u/bayhack May 08 '20
I am havng this strange import/export error when packaging a React context as a component: https://stackoverflow.com/questions/61649633/creating-a-npm-module-out-of-a-react-context
I organized the code in the StackOverflow post above with more info.
1
u/Jorick_DC May 08 '20
Hi,
I am trying a fucntion which I declared in a seperate file. When I clikc the button to fire the function nothing heappens can someone explain me what I am doing wrong.
EXAMPLE
Firebase.js
export const doSignOut = () => firebase.auth().signOut();
SignOutPage.js
import doSignOut from '../Firebase';
const SignOutButton = () => (
<button type="button" onClick={ () => doSignOut } >
Sign out
</button>
);
1
u/badboyzpwns May 08 '20 edited May 08 '20
trying to refactor my code. Is there a nicer way to do this?(without repeating the code)
1
u/GhostofBlackSanta May 09 '20
Hi, why is it that when you define a function inside of a component class, you don't need to write the word "function" in front of it? Is it automatically assumed somehow when its compiled?
1
u/[deleted] May 10 '20
Is there anyone writing out class components to production?
1
u/Supernumiphone May 11 '20
Using react-router-dom and so far can't find in the docs how to create a static link to a specific page in my app. So for example if I have an info page that I put at /info and create a link to it on the main page using react-router-dom, I can click the link to /info and I go there and it works. However if I type http://mydomain.com/info in to the browser, I get a 404.
I understand why it works this way, but I don't know what the fix is, or if there is any easy way to allow bookmarks to work in this type of app.
In case it matters, I'm serving the page using python/django. So when I go directly to the /info URL, I get a django 404.
My only guess at this point is to create a catch-all route handler in django that will redirect to the main page and then somehow have it navigate to that URL after the page loads. Maybe create a template variable that sets a JS variable that the react app can inspect and if it's set go directly to that URL? Seems a bit kludgy so I figured I'd ask in the hope that there's a better way.
1
u/fctc May 14 '20 edited May 14 '20
Do I have to lift all state up to be able to call a component functionally? Here is a minimal example of what I mean:
My understanding is that once I add the Toggle button, the Comp component is cleared from the process and the hooks are rendered out of order from what they expect. I'm trying to change my program over to a useReducer so it's easier to pass state back up the tree 5 levels, then down a different path. The problem is I'm not sure how I'm supposed to do this when I have to mix props and functional calls together, and am stuck either randomly trying different things, or trying to shoehorn my program into a pattern I see in a tutorial. I'm sure I'll get it this way eventually, but would really appreciate any pointers, thanks!
1
u/Marsfork May 15 '20
When running a react app using the typescript template, I need to restart the server between edits to see my changes, is this normal? When using a default js template updates are reflected immediately.
I created the app using
npx create-react-app my-app --template typescript1
u/[deleted] May 15 '20 edited May 15 '20
Why is this an error when I use both
numandobjtogether like this?The error is:
Cannot read property 'text' of undefinedThanks.
Parent
Child
1
u/diet_napalm May 18 '20
I'm confused at how this react component using the setState hook works:
The hook is called at the beginning of the function setting the state to a default of empty. Isn't the function called each time the component needs to be re-rendered? Wouldn't this reset the state to empty each time? I don't see how this works.
1
u/badboyzpwns May 19 '20 edited May 19 '20
I have a list of items, people can add or delete items in it via PUT or DELETE requests. The list of items is shared with all my other components. It works fine!
I want to put it in my portfolio. But!I don't want users to change my database but I want to showcase that it works. It would suck to have a random person visit the site and then delete everything. Any workarounds for this? I disabled the add/delete items feature for now!
If it helps, i used redux too.
1
u/diet_napalm May 19 '20
I have a couple of components that are using data from global state to calculate display values on render. They use the same core calculated values. My goal has been to avoid performing the same calculation separately in each component.
My current solution is to create a parent component that does the calculation, then passes the values to the children in props. Works fine since the two components are adjacent in the DOM. But what if they weren't, and it wasn't practical to use this approach?
How can two separate components share that sort of data?
1
u/[deleted] May 21 '20 edited May 21 '20
hey all,
can someone help me with understanding why a clearInterval or clearTimeout stops working when the setInterval or setTimeout contain a useState hook?
im trying to make a countdown timer like this:
calling countDown prints at second intervals to the console and calling clearCounter stops it as expected. but im trying to save the state like
and if i do this calling clear counter doesn't stop count from changing. thanks any and all
1
u/badboyzpwns May 22 '20
No software dev experience here!
How widely used is grpahql in the industry? I learned the concepts of it and I am aware of the benefits over REST but I feel like most sites can be done via REST!
But at the same time, you could argue every site can be made with GraphQL, it's just that the boiler plate code for graphql seems to be much more than React + Redux!
1
u/dissipatingheat May 22 '20
Learning React & Javascript in 24 hrs:
I need to rapidly make the frontend for a heart rate monitoring device. A team member is building the device, another person is working on the backend to communicate to the device and send me states, and I need to write the frontend that updates the states and can handle touch events. I plan to use React w/ Redux in vscode.
I have extensive experience with programming (data structures), systems programming, and machine/deep learning research (C, Java, Python...etc), yet I have not worked with JavaScript.
Any tutorials, courses, or websites I should go through will be greatly appreciated.
I would greatly appreciate any help. Thank you :)
1
u/pink_tshirt May 24 '20 edited May 24 '20
Let's say I am grabbing a new user from some remote API:
What is <any> exactly? Is it some kind of expectation of what that async function would eventually return?
1
u/kickthevidit May 24 '20
Hi, I am trying to work on a Kanban Board feature on a website using the Dragula API. The problem is that I have never used an API before and this is my first React Project, so I have lots of trouble understanding the documentation. Every example for Dragula React-JS that I have looked at feels like Martian. How do I go about understanding how I should work this API?
1
u/hemehaci May 25 '20 edited May 25 '20
If I use {this.strng} below, it doesn't render. If I use the variable without this, only {strng} then it renders on the screen.
'this' was supposed to refer to object that is called right? I am confused. import React from 'react'; import ReactDOM from 'react-dom';
1
u/mova May 26 '20 edited May 26 '20
I'm trying to update a field in State only when two other fields are not null. The field to be updated should simply calculate the difference between the two other fields. The updating works fine but the math is WAY off.
For example:water1=20water2=25consumption=-18 (<-- what!? This should simply be 5)
My code inside handleChange is:
I've tried to use the parseInt to make sure that it's not interpreting string values instead. But it seems I'm not completely successful with that.
The input fields look like this:
What am I missing here?
1
u/99thLuftballon May 26 '20 edited May 26 '20
Total react n00b here.
Is it possible to add a whole bunch of instances of a react UI component to an html page?
To give a simple example, there's a "ul" with 25 "li" elements inside it, can I target the li elements and replace every one with a react implementation of a list item that does cool stuff with the li content?
All the examples online show a single root element with a react app mounted to it, but could I, for example, create my own implementation of a "button" element and replace every html button on a page with it?
1
u/pink_tshirt May 28 '20
How can you combine two functional interfaces, for example:
Any way to type it nicer?
Perhaps, smth like
But how would you define those interfaces in the context of the React.FC ?
1
u/ctrl-r23 May 30 '20
Hi! I am developing a web application in which the user has to complete steps to finish a task. The steps are:
Every step has to be completed to finish the process and always in the given order.
My question is, how would you handle the step state and the data the steps need?
I was thinking of using react router and then give every step a page like /step1, /step2, etc. Then every time a step is finished I would call window.location. The problem is I'm not sure how would I give the next step the data it needs, like the scanned image in step 2).
Also, I'm not familiar with hooks, redux and context, maybe these can help me in any way?
Thanks!
1
u/happyapple10 May 30 '20
I'm pretty close to 100% noob on ReactJS, so my question may be pretty simple to answer.
I have two text fields, firstName and lastName, which I need to use logic on as either one changes. For example, if someone is typing into the firstName field, I have an onChange event that is triggered calling a method in the same component. I can access the value of the calling event item using event.target.value but I will also need the value from lastName text box as well.
What is the best way to get the additional textbox info into my method? Use document.getElementById('lastName') as a parameter in an error function calling the method in onChange? Or use document.getElementById('lastName') inside the method in my logic? Or is there a better way that I am not aware?
I want to use the best method possible, so I'm using the proper techniques going forward.
Thanks!
1
u/frsti May 31 '20
I'm running a file that *sometimes* works in Cmd prompt that just returns some values scraped by using cheerio and puppeteer
But now it's just causing my command prompt to hang and doesn't return anything - Not even a new C: line
Not sure If I've messed up my npm or not reset everything properly when I've restarted my PC?
3
u/Fienases May 11 '20
is it good to write your logic inside your context component?
here's an example: https://pastebin.com/e9Tr3Etm
1
u/badboyzpwns May 05 '20
React hooks question!
Is it possible to do this with hooks? or do I have to use classes?
I don't think this would work at all.
2
u/Jorick_DC May 02 '20 edited May 02 '20
hello I am trying to create an application where users only see profiles with whom they match. however, I have no idea how best to approach this matching. Do you have any tips or tutorials explaining this?
as a database I use Firebase.
thank you for youre time. :)
2
u/pruggirello May 02 '20
Hey fellas!
I'm making a sudoku-ish game, where the player has to guess what numbers are in the grid based on hints they receive about the numbers' mathematical relationships. So far so good, but now I've hit a snag. Below is the structure for the <Hints /> component
this.props.game is a reference to my new Game() in my App.js, which I have here:
This new Game() refers to my Game.js file which holds all the game's logic: the masterValues, userInputs, and the hints. The methods inside of Game.js, setHint() and getHints(), work perfectly for setting and getting new hints. Everything works, except I can't get my new hints to render. In my Hints component's render() function, I'm calling this.displayHints() to list the available hints, which works when the first one gets generated at the beginning of the game. After the user clicks the button, however, new hints are not being displayed even though I am calling the function again inside this.generateNewHint(). The console.log() is working and listing the appropriate hints. That's problem 1.
To solve this problem: I have tried switching .map and .forEach, I have tried setting hints to the <Hints /> state, and I have tried setting hints to the App.js state object. Neither .map nor .forEach works to render the new hints, just the first one. The latter two solutions didn't refresh the component when setState was called, which resulted in the new hints not being rendered.
Problem 2 is that my hints say "The number in [object Object] plus the number in [object Object] equals 0." It should be getting the key of the key/value pair for each individual number. This is should be something like A3, B1, C4, D2, etc. This corresponds to a square on the board at row Letter and column Number. The hints should read: "The number in A3 plus the number in C1 equals (sum of the two numbers)". The object that gets passed in looks like this: {A1: 24} The key is dynamically set and the value is randomly generated and then assigned.
So my quesitons are: 1. How can I get my list of hints to be rendered dynamically? What's the best way to do it? 2. How can I access the key and the value in my hint objects separately?
2
u/masterofmisc May 03 '20
Hi Guys,
I know that react is all about components and building them up. But I am stuck on how you lay them all out to fit your design on paper.
For example, say I want to make an Outlook clone with a tree view on the left and on the right side of the page, have it split horizontally. The top half would be a list of emails and the bottom half would be the email detail. Then at the top of the page, have tabs to flip between inbox, sent items, calendar, etc. When you click on a different tab it could totally change the contents of the main page.
In my mind I can see how to make all the individual components that do each thing, but I don't know how you would put them all together? How would you guys go about doing this? Is there a package you pull in?
Or do do you use a grid system? But then if its a grid system, how would you make the tree view panel resizable for example? (or is that advanced)
Thanks in advance.
2
u/Jorick_DC May 04 '20
Hi,
I am trying to create a registration page. I am already able to write data to Firebase database. However, I get stuck when I want to upload the profile picture to firebase and save the reference in Profile on the database. Does anyone have a good tutorial or tips for this?
Thank you for your time :).
2
u/Luke_Mudufi May 04 '20
So having this weird problem where my react app isn't showing anything to the browser and I'm not sure why it was working fine before I'm working through a Bootcamp and learning react and im completing lost on how to fix it
2
u/Ret_01 May 04 '20
I've recently been tasked with providing a new React based UI to an existing WebGL application (currently using Knockout) and am having some trouble figuring out how to handle sharing state between the UI and the WebGL application. The application must be able to trigger UI updates and vice versa.
So far I've tried to use the useEffect hook, which lets the UI update the application, but it requires diffing against previous state to detect when things have actually changed. I also have no idea how to get the application to update the UI without using an EventEmitter to trigger a full ReactDOM.render call.
Has anyone else had to deal with this sort of situation and if so how did you manage it? Are there any established patterns for dealing with it?
2
u/ytdl-node May 09 '20
If I am using React hooks, let's say for a state change, I'd normally write something like:
Now if I pass the
setUsernameandsetAgefunctions to a component let's say 'A' in the following fashion:And in my component 'A', I update the username and the age.
This will cause the main App to re-render twice right? Is it not better if I just use an
objectfor the state? E.G.:Why do we not use this instead?
2
u/[deleted] May 12 '20
Hi there, I'm new to React and am trying to create a workout tracker web application.
So far, I decided that when the app first starts, there will be a homepage that has 3 buttons: Create Workout, Select Workout, Stats. These options were created via the common component, WorkoutOptions.
Now, my goal is to be able to click select workout, and have a new Container component show up to replace the existing 3 buttons, essentially moving the user to the "next" page.
However, I'm unsure of how to do this.
In my head I'm thinking that if the App Component detects that selectWorkout is clicked (via event listener), it will render <Container/> and unrender(??) the Option Cards
However, that clearly doesn't sound right so pointers would be much appreciated
2
u/089-083 May 22 '20
Hey guys - I was able to build a small application that takes input, uses the input to call an api, and displays the results from the api. Let’s call this the platform.
How do I go about making another page, let’s say a landing page, where I can login and signup before being able to access the platform?
I have only used react for this application so far, nothing server side yet.
2
u/[deleted] May 22 '20
Noobie here with a few questions, the first one is as simple as it gets and I thought I knew the answer to it. In the following code I expected to only log to the console once as the state is set before rendering and therefore a second render should not happen because the state never changes but rendered is logged twice.
The second question I have no code example for but the issue I have is using the response from one http call as a part of another http call that immediately follows the first. I'm using async/await and putting the response in state but as setting state is async the second call starts using an undefined value. What's the best way to handle this? Thanks in advance for any help.
2
u/Cannabat May 24 '20
I am working on a hobby project that has some very CPU intensive reducers in redux. I’d like to explore running those reducers in a web worker.
It looks like I could extract the reducer code to a module and use
worker-loader+comlink+redux-thunkto do the work asynchronously.Am I thinking about this correctly? This is a bit outside my comfort zone, appreciate any advice!
It may be simpler to not use redux and switch to context when using webworkers, but the redux dev tools and packages like
redux-persistare really nice to have.2
u/cmaronchick May 26 '20
What's the preferred way to fetch data when a user navigates via React Router?
My best assessment at the moment is that if you have a standalone page (ie a user can navigate directly to it), it's best to make it a class so that you can check the state and fetch data if the route parameters are updated, but I wonder if I am missing something obvious.
FWIW, I'm using Redux with React Router. Thanks in advance.
2
u/konaraddi May 28 '20
I have a simple component that React calls 2*(N+1) times where N is the number of state changes:
https://codesandbox.io/s/stoic-goodall-2tvxn?file=/src/App.js
Why does this run 2*(N+1) times (as opposed to N+1 times where N is the number of state change and +1 is from the initial render)?
1
u/iTsHutchy Apr 30 '20
Im new to react - ive built a few static page websites (2-3 pages) looking how I can integrate with databases and expand my knowledge and learn what react can offer for my development is there any quick resources I can take a look at
1
u/cmaronchick May 06 '20
I am working with the Spotify APIs and authentication and am a bit frustrated by the relatively short expiration time of the access token.
I tried using jwt-decode to check the expiration date/time, but I get an error because the Spotify access token uses _ rather than "." (I think; I get an error anyway whenever I try to decide the Spotify token)
Are there other libraries out there that people like for deciding JWTs?
My other thought is simply to refresh the access token with each Spotify call, but that seems excessive and I worry it wound affect performance.
1
u/CYMAD May 08 '20
Hello, In material UI documentation I found something that Ive never seen before. Can someone explain to me what this is ?.https://prnt.sc/sdcyc1. And If i turn it to a regular ES6 arrow function, i get this error https://prnt.sc/sdczmu . What is exactly happening here ?
https://material-ui.com/components/lists/
Thank you :).
1
u/pink_tshirt May 09 '20
Do you normally write action creators or dispatch straight from your components?
1
u/DeadeyeDuncan May 10 '20
What exactly is react native and react redux?
As I understand it, react native is for phone app development and react redux is basically the express.js to react's node.js? ie. Simplifies and adds useful functions.
I haven't used react for a while, and rather than relearning it (a lot seems to have changes), I'm thinking of diving straight into learning redux - is this advisable?
1
u/TubbyChaser May 12 '20
I've been creating a Todoist clone, but can't seem to properly implement inline tagging. I know how to identify and store the tag using RegEx, but can't figure out how to format the text in real time after the user has prefaced a word with a #.
From my research, it seems that this isn't possible using a standard input (e.g. textarea) and instead maybe need to use a div with contenteditable? Would Slatejs or another rich text editor framework help me here? They all seem too complex for my needs.
Any guidance would be amazing!
1
u/waresoft77 May 12 '20
What is the best way to fetch data from a graphql endpoint on the client? I've tried setting up Apollo (love the websocket support) but it's extremely difficult to get working.
I'm using NextJS, so it's important that the data fetching is purely performed on the client. I had problems where I was initializing the client during server-side rendering, and I wasn't sure how to avoid that.
1
u/Daebak404 May 12 '20
Hey, I am a beginner looking for working on a react project for free. If anyone needs help with their project let me know ☺
1
u/2wistd May 12 '20
New to react, but I have a project I'm working on. I have a webserver (apache) on my raspberry Pi, and a few Pi Zeros to act as web browsers locally. I am setting up a pi as a Nas server for my photos. I want to use react.js to have the pi zeros browse to the apache server and see a sideshow of the images. I want to be able to filter the images by date, rating and tag. Would I be better of loading those images into a db and have the browsers pull that data or what? I want to do the filtering from one device yet show on each device. Thanks for any help
1
u/badboyzpwns May 13 '20
Sorry if this dosen't belong here! I have a question about axios!
I made a json data that I stored in a JSON Storage online (called jsonbin)
Here's what it looks like when the base url is called.
Code:
I only want axios to return the first object with an id of 7, instead of the whole streams database. Is it possible to do something like:
I get an route error while doing so.
1
u/Spiritual_Salamander May 15 '20
My friends wants me to make a simple blog for her. Mostly just a static web page along with functionality for making comments and such, nothing else. I mean she could just simply use wordpress or something but I figured I could just make it and put in my portfolio.
All other front-end type of projects I have done before I have done using the create-react-app, but I heard this has terrible SEO. What would be a better alternative ? I figured this would be a good time to checkout GatsbyJS or NextJS or something along those lines and step away from the create-react-app for a bit. Any recommendations ?
1
u/[deleted] May 16 '20
Hi there, I've been pretty confused as to how to use States to pass information from the child back to the parent and would really appreciate some guidance!
Currently, I'm trying to create a Workout app where the homepage contains two options: 1.Select Workout 2.Create Workout
I want to make it possible for one to click on "Select Workout" and go to a "new page" with a different container Component.
However, I'm confused by which component should own the onclick event listener.
Currently, my Component Hierarchy is as so:
App.js
Homepage
I think that the component OptionButton should have an event listener that detects when a button is clicked. But the problem is, there are 2 items that use the component OptionButton (Select Workout and Create Workout), how would the program know which of the two buttons was clicked and how would it store that info to be passed back to the parent component?
Currently, they are rendered as two different objects under Homepage.
return( <div className='flex-container'> <OptionButton id = {1} info= "Create Workout"/> <OptionButton id = {2} info = "Select Workout"/> </div>Thank you so much!
1
u/ryanz67 May 16 '20
I have a simple react application kind of like a paint application. I’m wanting to add a feature where I can undo and redo changes made, would I be best to add something like redux so I can keep a track of history changes ?
1
u/Previous_Advertising May 16 '20
Hey! I posted a question yesterday but got no reply. I hope someone can explain this https://www.reddit.com/r/reactjs/comments/gke4fa/issue_with_material_ui_slider_in_next_js/
1
u/Roly__Poly__ May 17 '20 edited May 17 '20
I'm having a heck of a time trying to understand how to use this Higher Order Component supplied to me from a tutorial.
My understanding is: Without this HOC, I would have to put Authentication logic into every component on my site. So what this HOC does is extract that logic, store it, and "wrap" its contained component, injecting (somehow) Authentication logic in the process.
meaning, the HOC, called withAuthentication, should at least pass its state(?) down to the component it is wrapping. I believe there is something else going on with the Context API that I need explained too...
Here is the code:
So I see the following: in componentDidMount(), there is some code that runs onAuthStateChanged "sets an observer" (see link below) that essentially gets the User object from Firebase Auth. Then that authUser object is stored under authUser in component state. And hypothetically I can do something with that stored User object, only, I don't know how to access it in the wrapped component?
all my Google attempts returned StackOverflow links about passing state from child to wrapper, not wrapper to child.
Next in componentWillUnmount() there's "this.listener()" which I do not get. The tutorial said it was to prevent memory leaks.
Lastly there is something going on with the COntext API and this HOC... The HOC is passing its component into the AuthUserContext.Provider. The question is what does that do for the wrapped component? Can I access the value passed to "value" in the Provider somehow?
My goal is to do something like:
So basically I am trying to figure out how to get the name of the authenticated user in the InboxPage component. But more than that, I want to understand how HOCs and the Context API works: "How do I pass data between HOCs and their wrapped component?" "How can I get that 'this.state.authUser' I see being passed into the Context.Provider?"
The docs weren't helpful for my objectives.
edit: I tried making a new HOC, "withContext", like what's said in this link: https://stackoverflow.com/questions/49870098/how-to-get-the-data-from-react-context-consumer-outside-the-render but it did not work. the wrapped component's "this.props.value" logged null instead of the User object I was hoping for.
https://firebase.google.com/docs/auth/web/manage-users
1
u/Roly__Poly__ May 18 '20 edited May 18 '20
Anyone experienced with combining React and Firebase? Please comment if you're available for between 2 and 5 hours a week for the next month or so. I'd like help on a project. Will pay (a little)
edit: I can do what I want when it's just Firebase and JavaScript, but when I throw React into the mix I get strange and/or unpleasant results. Send help
1
u/[deleted] May 18 '20
What PC specs do employers look for in remote react jobs?
I currently have a budget for a core i3 8gb laptop. would that be enough?
1
u/EnderMB May 18 '20
I applied for a software engineering role at a large bank, and their tech team decided that I would be a better fit for a full-stack role, considering my experience.
I'm pretty sure they're going to ask me a bunch of React questions, and while I've worked with Node/Express in the past, I've never used React. I've got two days until the interview.
Am I fooling myself in thinking that I could learn enough React to pass a basic interview?
1
u/bill10351 May 18 '20
Hi there!
I'm trying to build a simple blog using test data.
Trying to figure out why reloading the page breaks my component. I'm fetching all the data in the App component and passing these down via the Routes. It works great if I start at root, but if I navigate to a detail page and reload, it breaks and returns " TypeError: can't access property "userId", selPost is undefined ".
I think it might have to do with how I'm fetching the data, but I'm not sure about that. Any help is much appreciated.
The App component:
The postDetail component:
1
u/Cranzy May 19 '20 edited May 20 '20
I am a full stack c# dev and doing web apps where the frontend is usually just html css jquery.
I recently jumped in and completed the React course on Scrimba, which I thought was great intro into React, especially as you pause and alter the code to see what happens.
I am thinking it might be a good idea to do another course but not sure which one to go for. The full react course on scrimba or the one from Tyler McGinnis. Both are paid courses so I'm not sure which would be better for me and the background I have around coding in general already.
Or should I really be doing another course at all now that I have the basic. I can just start building things and learn as I go.
1
u/Chr0noN May 19 '20
How do companies handle updating their react code in production? I see articles suggesting to use "service-workers" and use the "skipWaiting" feature with the notification "Update Available" with an update button. But I've never really seen the idea of "updating" a web app anywhere. So how do they do it?
1
u/[deleted] May 19 '20
I'm learning React on Scrimba and am really enjoying the layout of the program they're using: https://imgur.com/SLtOkBC
Does it have a specific name (so I could download it and use it) or is it Scrimba's own thing?
1
u/Spaceman776 May 19 '20
When do you use componentWillMount()? I'm reading that it gets called right after the constructor and before render() so why can't you just put whatever is inside there in the constructor instead?
1
u/1awrent May 19 '20
Hi !
I'm having trouble on an app that allows users to store & view 'benchmarks'.
I got to the point where a user can upload & view these 'benchmarks' successfully, however I'm trying to implement a search function to filter the viewable benchmarks. The way I thought this would work is that I would pass the list of 'benchmarks' to the child component that is doing the rendering and set a 'filtered' state within that component where once the user inputs anything into the search bar, this new 'filtered' state would only have the 'benchmarks' that match up with the inputted values and then of course render that new list...
Currently I'm running into an error where my loadData function that actually maps everything out is breaking as the list is 'undefined' - also tried to set a condition within the render so if the filtered list is not defined it would just render the original list anyway (this.props) however it still breaks but it will work if I hard code "this.props" as the value to map over which is the real confusing part...
Sorry for the wall of text! I'll post the code now - appreciate any help.
Included the main component in question as well as the parent component to be safe: https://gist.github.com/lydco/5d5a2af46670a3bd08636ece6b1c3eb3
1
u/Jorick_DC May 20 '20
Hi,
Can someone help me? I try to show te username and picture in the navbar after the user logged in but i cant seem to retrieve the user details i saved in firestore. I try to do this with the useEffect hook but it loads before the authenticated user is loaded from the context. Which returns a null error
1
u/iTsHutchy May 20 '20
I have an interview test to prepare for and they are wanting me to hook a node api into the front end react - can anyone suggest some good approaches to take with this any help will be amazing :)
1
u/[deleted] May 21 '20
So I'm watching the Scrimba tutorial for React (created 2 years ago) and the guy is using React version 16.3 and talking about how "hooks" are the new thing and he believes they'll make class components unnecessary. Did this end up happening?
I was just getting the hang of class components too...
1
u/badboyzpwns May 21 '20 edited May 21 '20
I'm a bit confused on how to use axios in React with express framework for node.js.
My proxy for express is on port 5000;
This would work if I'm on localhost:3000:
But when I host the actual website, GET in express doesn't work.
Any ideas why?
1
u/oldeback May 21 '20
Hello, does anyone have any tip on some learning react guide that is audio only? Like a podcast. I'd like to listen to something for example at the subway. I want them to talk about how react works and the code and not random stuff all around the subject.
I know it's probably not the best way to learn but it's still better than nothing!
1
u/netrunner18 May 21 '20
How do I render an iframe after the video is loaded in react? I am trying to embed facebook video in my react app using the iframe but I keep getting
on the video. Also, for some reason the video pauses even if I click outside the iframe. How can I turn that off?
1
u/badboyzpwns May 22 '20
How do you do axios.post(URL, {}) to a specific property in a JSON database?
I have this!
https://music-json-server.now.sh/db.json
I want to axios.post to streams array!
I have this so far...
1
u/089-083 May 22 '20
I am trying to create a navigation bar, and am using react-bootstrap and react-router-dom. Here is my code:
<Route component = {Home} exact path = "/" /><Route component = {Platform} path = "/platform" /><Route component = {About} path = "/about" /><NavLink to = "/about">About</NavLink><NavLink to = "/platform">Platform</NavLink>But when I click on the link, say, "Platform", it doesn't show me the platform page. What could be the issue?
1
u/Abyx12 May 22 '20
I've the necessity to have my react app served by a Java Spring server. Do you have any idea how to do? Best practice?
1
u/g-six May 22 '20
First off, I am not a novice programmer but I have absolutely zero experience when it comes to website development. I want to build a react website to learn some new skills in this area.
A little description: Lets say I want to build a website where the user can type in some data, and then when he is done he can download the data as an .xml file or something similiar (just to save it locally). After downloading the file the user should be able to upload the file again and reload the data in the application. Basically I want to make an online data manipulation tool without a database.
But I have a few questions on how I should approach this. First off, does the user really need to upload the xml file to the server or is there a way to just load the data another way since technically the javascript is running on the local webbrowser? I don't really need the xml file saved on my server.
All the things I found with google are more into the direction of how to generally upload files but not how I can work with them. Even if I would use this approach, how would this work with multiple users? Would I need to build a complete serverside application (with node.js or similiar) to handle the incoming xml files?
If somebody has a general point of direction for me which keywords I could google, or maybe the names of a few packages or a tutorial that might help me, that would be greatly appreciated.
1
u/BlazinAsian03 May 23 '20
I'm currently working on my first React project and am having problems accessing the right JSON values:
In my component, I have a variable called selectedExam which is passed in as a prop. I am then trying to show a row in a table for each section in the selected exam.
In my markup I have this to show a new table row:
If I change the above line to
everything compiles and a table row is shown, and section.name shows the exam name (i.e. "First Exam" or "Second Exam"). Once I add ".sections" to try and go down one level further, I get this error: TypeError: Cannot read property 'map' of undefined.
1
u/I_am_echelon May 23 '20
Does anyone know a fairly straightforward way to create a touchenter & touchleave event in react? onTouchMove fires constantly and I'm not sure how to parse that data to just fire when the touch enters a specific element. I'm using typescript but feel free to respond using regular js.
Also if anyone knows why they removed touchenter and touchleave from the spec I would love to know the reasoning behind it. Seems like it just complicated things for no real benefit..
1
u/[deleted] May 25 '20
I have a simple comment system built on my Gatsby site, and I want to implement something like Wordpress' comment-reply.js.
Goal: a reader can click "Reply" on any comment, and the comment form will 'jump' under the comment (e.g. <li id="commentid-8584">). If they click "cancel reply", it will jump back to where it was.
What's the simplest way to move an element onClick like this and then back again if the user cancels?
1
u/GhostofBlackSanta May 25 '20
Hi I’m currently working through Tyler Mcginnis’s React class and was going to do his React Hooks class immediately after. When I’m done, I was going to start my own project. Would these two courses be enough to get me started or should I learn other tools like Redux before?
1
u/Jorick_DC May 26 '20
Hi,
when a user is logged in I would like to display in the navigation a small version of profile picture and name of the user. Does anyone have any tips on how to do this best? I use React hooks and firebase. The user is stored in firestore database.
1
u/[deleted] May 26 '20
Couple of questions. I've made a very basic website (just some hyperlinks in the footer) because I'm new. and I get these two errors whenever I start my website:
These errors go away when I disable adblock (even though there are no ads on my site). Could someone explain why this happens? Thanks!
1
u/Spaceman776 May 27 '20
Hi, I'm learning React hooks after just finishing regular React and I am confused why we have to use a function inside of useState when setting the state based on the previous state. For example, in a todo list we use
I tried using
and that worked just as well. Is there something I am missing on why we use the first method instead of the second?
1
u/Jorick_DC May 27 '20
Hi does anyone have any tips on how to automatically resize an image and still maintain aspect ratio before uploading this file to database?
1
u/[deleted] May 28 '20
Hi, im creating a react shared component library and I'm not sure how to handle CSS.
Currently when I use the component library in a project I just load all the CSS into that project but it is possible to break up the CSS per component so I'm loading the CSS with the component?
For example instead of doing:
Would I do:
And have that import the styling the CommonGrid needs?
This is what I used to build my library: https://github.com/transitive-bullshit/create-react-library
1
u/Silly-Freak May 28 '20
I'm trying to make my dialogs usable and was thinking about giving them a promise-based API - using a hook that looks like this (sandbox):
Usage looks like this:
I have already identified some issues here, such as multipe
show()calls before a re-render not triggering an error because theif (resolve !== null)condition won't identify the change; same for multiplehide()calls. However, when I would change this to use functional state updates, I think I'm not even able to throw an exception to my caller, correct? I'm not really too concerned about that, because those are assertions anyway and shouldn't be able to happen, but then there's also the side effect of resolving the promise inhide. Doing that in a state updater is also not clean, no?But the main issue is in the
onClickhandler: after theawaitpoint, the async function will still have captured old state from when the click event happened, so when processing the result I won't be able to access any state without keeping in mind it's probably stale.Being able to say
result = await dialog.show()seems so desirable, but it also looks like using async functions at all is a huge footgun with how capturing of state works. Is there any way to achieve this API safely?1
u/[deleted] May 29 '20
I'm working with a shared component library using Yarn Workspaces. Am I supposed to commit the /dist folder from my comment library or should I need a way to have that generated when importing it into my application?
I forgot to commit it so when my team pulled master they got a reference error when trying to use something in /dist
1
u/JSavageOne May 29 '20
`useRef()` accepts as a parameter a so-called initial value, yet when used on a <input /> the value doesn't show up.
The input box just shows up empty.
I wanted to avoid dealing with the `useState()` , `value={state}`, `onChange()` boilerplate for a simple input element, and thought I could use refs, but seems that that's not possible. Why doesn't the input box display the initial value specified in `useRef()`?
1
u/mashlautertun May 29 '20
I'm working on an app that requires oauth authentication to Instagram. I'm able to complete the authentication without issue but I'm struggling with keeping state after being redirected to the IG login screen.
I built a component that handles the login, callback, etc, that I'd like to be able to reuse across my app in different places. After login is successful I'd like to make sure I'm still on the page where I initiated the login (eg. user profile page).
When IG authenticates I need to redirect to the IG login page which I in turn provide a callback url to. Initially, I was able to work around it by popping out a window and using local storage but I don't want to use a window when on mobile. For this I have a route the directs to my component, and once completed I can use history.push to get back to the profile page, but I can't figure out how to make the push to the calling page dynamic. Is there a better approach to this? Will context API survive a redirect?
1
u/[deleted] May 29 '20
I'm making attempts to get out of tutorial hell and create a very basic game for myself.
I've mocked out the design in Figma to have 3 different screens, with each showing specific components for that screen or page:
I'm pretty new to this but in my mind I'm thinking I need to use React-router as there are different pages. So how do I pass my state around the different routes? Is this a situation to use Redux? Is that what is still commonly used? Additionally I'll also be storing data from state into my localStorage when the game is finished and then eventually into a database but just taking baby steps.
1
u/koeniedoenie May 31 '20
I have this very basic function to call a function in another file, though what happens is that it constantly tried to call this function and thus keeps on loading. How do I make it so it only calls this function once once I load the page?
export default function App() {const {events,error,loading} = CallAPI()return (<div>{events.map(event => {return <div key={event[2]}>{event}</div>})}<div>{loading && 'Loading...'}</div><div>{error && 'Error'}</div></div>)}1
u/[deleted] May 31 '20
I would like to have one image as the footer of my website with text overlayed on top of it in different sections.
This is my image and I would like words in each of those blocks. Is there a way to do this on one fell swoop/component or would I need to divide the image into 6 different components and have the footer render all 6 side-by-side? Thanks!
1
u/SpicyT21 Jun 01 '20
Hello! I've been learning react for a while and made this template with animations, I would like to have some feedback, hope you like it https://codesandbox.io/s/profiletemplate-zz2lg
0
u/[deleted] May 10 '20
[deleted] — view deleted comment
0
u/[deleted] May 12 '20
[deleted] — view deleted comment
0
u/[deleted] May 02 '20
[deleted] — view deleted comment
0
u/[deleted] May 04 '20
[deleted] — view deleted comment
0
u/[deleted] May 14 '20
[deleted] — view deleted comment
0
u/[deleted] May 21 '20
[deleted] — view deleted comment
0
u/[deleted] May 21 '20
[deleted] — view deleted comment
0
u/[deleted] May 27 '20
[deleted] — view deleted comment
0
u/[deleted] May 28 '20
[deleted] — view deleted comment