Posts

Showing posts with the label reactjs

Disable switch button in React

Image
Disable switch button in React If I click on the Annual radio button, then switch button (labelled "half day") should be hidden or disabled (only for Annual radio button). How do I do this in React? <RadioGroup onChange={this.onChange} value={this.state.leavevalue}> <Radio value={1}>Casual</Radio> <Radio value={2}>Medical</Radio> <Radio value={3}>Annual</Radio> <Radio value={4}>Lieu</Radio> <Radio value={5}>Special</Radio> <Radio value={6}>Maternity</Radio> <Radio value={7}>Paternity</Radio> <Radio value={8}>NoPay</Radio> </RadioGroup> This is my switch button code : <Switch onChange={this.handleHalfDay} checked={this.state.isHalfDay} /> This is my onChange function: onChange = (e) => { this.setState({ leavevalue: e.target.value, isHalfDay: false, }); } My radio buttons and the switch button: ...

Can't get store value after the value was updated using React

Can't get store value after the value was updated using React I have a SearchBar component and it has a subcomponent SearchBarItem. I passed the method handleSelectItem() to subcomponent to dispatch value to store and it works (I saw it from the Redux tool in Chrome). handleSelectItem() Then, when I tried to get the value from the method submitSearch() , which I also passed it from the parent component, it shows: submitSearch() Cannot read property 'area' of undefined. I'm still not so familiar with React. If someone can help, it will be very appreciated. Thanks in advance. This is parent component SearchBar: class SearchBar extends Component { handleSelectItem = (selectCategory, selectedItem) => { if (selectCategory === 'areas') { this.props.searchActions.setSearchArea(selectedItem); } } submitSearch() { console.log(this.props.area); // this one is undefined } render() { return ( <div className="searchBar...

API Fetch failed with No 'Access-Control-Allow-Origin' header is present on the requested resource

API Fetch failed with No 'Access-Control-Allow-Origin' header is present on the requested resource I've been running out of my mind trying to deal with this problem. I'm running React.js on my local machine under http://localhost:3000 and i'm trying to use the fetch method to load some data from http://api.population.io:80/1.0/countries http://api.population.io:80/1.0/countries According to the API owner "The standard response format is JSON (application/json) with CORS for cross-domain requests." I've tried various combinations of headers and what i have right now is this setup: fetch("http://api.population.io:80/1.0/countries",{ method: 'GET', mode: 'cors', headers: new Headers({ "Content-Type": "application/json", 'Access-Control-Allow-Origin':'*' }) }) According to Chrome, the following headers are being sent through the request: Access-Control-Request-Hea...

Problems Importing Bootstrap Studio Renders into React with reactstrap

Problems Importing Bootstrap Studio Renders into React with reactstrap I'm working on a project where the designer is working with BootStrap studio, which exports to html with BootStrap 4, and I'm converting the exported file into React components with reactstrap. I'm facing problems with class and styling rules, since the original file inherit from 7 different files. What's the best way to convert something like: <div id="nav-bars"> <nav class="navbar navbar-light navbar-expand-md" id="top-nav" style="background-color:rgba(0,0,0,0.5);color:rgb(255,255,255);"> <div class="container-fluid"><a class="navbar-brand" href="#" style="background-image:url(&quot;assets/img/logoalt copy.png&quot;);padding-right:5px;background-size:contain;margin-right:0;padding-left:5px;background-position:center;">&nbsp; &nbsp; &nbsp; &nbsp...

componentDidMount not being called after goBack navigation call

componentDidMount not being called after goBack navigation call I've set up a StackNavigator which will fire a redux action to fetch data on componentDidMount , after navigating to another screen and going back to the previous screen, componentDidMount is no longer firing and I'm presented with a white screen. I've tried to reset the StackNavigator using StackActions.reset but that just leads to my other screens not mounting as well and in turn presenting an empty screen. Is there a way to force componentDidMount after this.props.navigation.goBack() ? componentDidMount componentDidMount StackActions.reset componentDidMount this.props.navigation.goBack() Go Back Function _goBack = () => { this.props.navigation.goBack(); }; Navigation function to new screen _showQuest = (questId, questTitle ) => { this.props.navigation.navigate("Quest", { questId, questTitle, }); }; How are you rendering your components? It might be...

How to use camera roll image in webview react native?

How to use camera roll image in webview react native? I'm trying to capture image from a webview in react native and then display the same on my html page. Problem: I cannot access camera and save images from webview. Solution: I am capturing and saving the images using react-native-camera. Next Problem: I want to display this above saved image in my webview and then save it on a server. Note: My page is able to capture and save the data on server when i am opening it in a browser. I am facinf issues with webview in react native. mywebview.js file import React from 'react'; import { StyleSheet, View, WebView, ActivityIndicator } from 'react-native'; const HtmlPage = require('./index.html'); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center' }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 10 } }) class WebViewScreen ex...

React Tutorial: TypeError: Cannot read property 'props' of undefined

React Tutorial: TypeError: Cannot read property 'props' of undefined I decided to learn React and started with the official tutorial. All is good until I get to this state of my code: var CommentBox = React.createClass({ render: () => { return ( <div className="commentBox"> <h1> Comments </h1> <CommentList /> <CommentForm /> </div> ); } }); var CommentForm = React.createClass({ render: () => { return ( <div className="commentForm"> Hello, world! I am a comment form; </div> ); } }); var Comment = React.createClass({ rawMarkup: () => { var rawMarkup = marked(this.props.children.toString(), {sanitize: true}); return {__html: rawMarkup}; }, render: () => { return ( <div className="comment"> <h2 className="commentAuthor"> {this.props.author} ...

Redux-Form set component state based on initialValues

Redux-Form set component state based on initialValues I have a react form that is dynamically generated via data from DB. The issue I'm currently trying to solve is how to enable/disable "child" inputs based on the "parent" input (typically a checkbox). My plan was during rendering of the form I would create component state settings (parentClicked1, parentClicked2, etc) based on initialValues that are populated by redux-form. The name of the component state setting would correspond to the parent input name and would be passed to an onClick method. for example: const renderSettings = ({ fields, meta: { touched, error, submitFailed } }) => ( <div> {fields.map((setting, index) => ( <Field name={`${setting}.value`} type={fields.get(index).inputType} component={renderField} label={fields.get(index).labelText} format={(value, name) => { return setBoolValue(value) }} onClick...

React JS routing not working (Uncaught TypeError: Super expression must either be null or a function, not object)

React JS routing not working (Uncaught TypeError: Super expression must either be null or a function, not object) I am developing a simple web application using React JS. I just started using React JS a few days ago. Now working on the routing part following a tutorial. But my code is not working. This is my entry js file. import React from 'react'; import { render } from 'react-dom'; import ListComponent from './list.component'; import AddItemComponent from './additem.component'; import AboutComponent from './about.component'; import { Router, Route, browserHistory } from 'react-router'; //Create class TodoComponent extends React.Component{ constructor(){ super() this.state = { todos : [ "Wash up", "Eat some KFC", "Take a long nap" ], age: 30 } } render(){ var ager = setTimeout(()=> { this.setState({ age: this.state.age + 3 }) }, 3000) return...

Unhandled rejection using setState in .map loop

Unhandled rejection using setState in .map loop I am trying to setState within a loop but receiving Unhandled Rejection (TypeError): Cannot read property 'state' of undefined as an error. setState Unhandled Rejection (TypeError): Cannot read property 'state' of undefined The loop contains API data that is contained within another state and within this loop I am trying to setState using onClick= {() => this.setState({clicked: !this.state.clicked})} to change the className of an div as className={this.state.clicked ? 'closed' : 'open'} . state setState onClick= {() => this.setState({clicked: !this.state.clicked})} className div className={this.state.clicked ? 'closed' : 'open'} I have never come across this issue before but granted I haven't used within a loop before either. Here is a stripped example of the code class Rates extends Component { constructor(props) { super(props); this.state = { dailyRatesDate...

Reuse generic component functions

Reuse generic component functions I'm a very new React programmer and I have no idea how to fix this. In all my forms I have the following code parts. updateFormData(field, event) { const { formData } = this.state; this.setState({ formData: { ...formData, [field]: event } }); } componentLoaded = (field, data) => { const { loadedComponents } = this.state; var fieldName = field + "IsLoaded"; this.setState({ loadedComponents: { ...loadedComponents, [fieldName]: true } }); } allComponentsLoaded() { const { loadedComponents } = this.state; console.log(loadedComponents); for (var o in loadedComponents) { if (!loadedComponents[o]) return false; } return true; } updateFormDateData(field, date) { var value = date != null && date.isValid() ? date.toISOString() : null; const { formData } = this.state; } When in C# I would put this in ...

Chained fetches dependent on each other

Chained fetches dependent on each other Take the following scenario: I need to show in a table a list with all countries and the population of each country. All data can be queried from here: api.population.io. Thare are 2 api calls that can help me achieve what i want: As you can see i need to make 2 api calls since the second call is dependant of the name of the country made by the first call. I managed to make it work with the initial api call using fetch by using this code: fetch('http://api.population.io:80/1.0/countries') .then(results => { return results.json(); }).then(data => { //data.countries }) This just returns me a list with all the countries. Now i need to loop through data.countries and make a new api call for each country without breaking the whole process. I tried throwing another fetch call where data.countries is available while looping over data.countries but as you can imagine this breaks up the whole process, what i ...

Working with react : "cannot read property 'lat' of undefined

Working with react : "cannot read property 'lat' of undefined I would like to mention it that I am new to react,this is my first try. For the course I am following I need to create a single-page-app which loads google maps api and shows markers from foursquare. I have an issue when I try to load up the markers,there is an error "cannot read property 'lat' of undefined,it has been many hours since I am trying to solve this issue and simply I can not get the hack of it. I was wondering if anyone can help. I read through a lot of questions here but none seem to offer a solution. I have attached a screenshot of the error and my code. class App extends Component { state = { locations: , venueInfo: {}, query: '' } componentDidMount() { this.setState({ isLoading: true }); // Foursquare api request fetch(`https://api.foursquare.com/v2/venues/explore?ll=34.9003,33.6232&client_id=${Credentials.client_id}&client_secret=${Cred...

React Native Debugger state undefined

React Native Debugger state undefined I am trying to use the remote React Native Debugger for my project. I have installed React-Native-Debugger on my Mac with $ brew update && brew cask install react-native-debugger . Then I added Remote-redux-devtools package with npm install --save-dev remote-redux-devtools $ brew update && brew cask install react-native-debugger npm install --save-dev remote-redux-devtools My createStore code looks like this atm. import { createStore, applyMiddleware } from 'redux' import { composeWithDevTools } from 'remote-redux-devtools' import thunk from 'redux-thunk' /* some other imports */ const composeEnhancers = composeWithDevTools({ realtime: true, port: 8000 }) export default createStore(rootReducer, composeEnhancers( applyMiddleware(thunk.withExtraArgument(api), logger, firebaseSave) )) Console output works just fine, but it is not picking up on the actions or redux state. Am I missing a step? Why isn't it ...

this.setState doesnt change the state

this.setState doesnt change the state So, I am trying to change the state using previous state, but it doesnt change whatsoever. Can anyone tell me whats the problem pls? handleToggleComplete = (key, complete) => { itemIndex = this.state.items.findIndex(item => item.key === key); console.log('before: ', this.state.items); this.setState(prevState => { return { ...prevState, items: [ ...prevState.items, prevState.items[itemIndex]: { completed: true, text: 'hardcoded value' } ] } }); console.log('after: ', this.state.items); } Logs: before: [{…}] {key: 1530370127933, completed: false, text: "some value"} after: [{…}] {key: 1530370127933, completed: false, text: "some value"} 1 Answer 1 t...

Automatically going to a div element created in React Virtual Dom

Automatically going to a div element created in React Virtual Dom My webpage uses React components. At the render function of one of its components div elements that looks like: <div id='myid'> {/* ... */} </div> are being used. After reloading a page we need to go to one of those divs. For example, after reloading that page we could automatically need to go to the <div> element with id equals to myid . Notice that that <div> is in React virtual DOM so functions like document.getElementById might not work (as it is happening with me). Is this possible? <div> myid <div> document.getElementById 3 Answers 3 The <div> and the id will end up in the document when the component is mounted, so you could scroll there in the componentDidMount hook. <div> id componentDidMount Example (CodeSandbox) class App extends React.Component { componentDid...

GET with query string with Fetch in React Native

GET with query string with Fetch in React Native I am making a request like this: fetch("https://api.parse.com/1/users", { method: "GET", headers: headers, body: body }) How do I pass query string parameters? Do I simply add them to the URL? I couldn't find an example in the docs. Possible duplicate of Setting query string using Fetch GET request – Hirurg103 Jun 30 at 14:29 4 Answers 4 Your first thought was right: just add them to the URL. Remember you can use template strings (backticks) to simplify putting variables into the query. const data = {foo:1, bar:2}; fetch(`https://api.parse.com/1/users?foo=${encodeURIComponent(data.foo)}&bar=${encodeURIComponent(data.bar)}`, { method: "GET", headers: headers...