I have this route
<Route path="/Info/:id/:name/:type">
<Info />
</Route>;
And this is Info Page
export default class Info extends React.PureComponent {
public state = {
}
componentDidMount () {
}
render () {
return (
<div>
this is info
</div>
)
}
}
How do i get query strings id, name and type to info
Try useParams from react-router-dom.
ie;
import React from "react";
import {
useParams
} from "react-router-dom";
export default class Info extends React.PureComponent {
componentDidMount() {
}
render() {
let { id, name, type } = useParams();
return (
<div>
this is info
</div>
);
}
}
You can use the match object of react-router.
Class Info extends React.PureComponent{
render(){
return(
<h2>{this.props.match.params.id}</h2>
)
}
}
Read more on match object here
If you are using react-router-dom 5.1
Then you can use the useParams.
Read more on useParams here
Related
My Parent component is like - Requestdetails component
import React, { Component } from "react";
import TopBarComponent from '../../common/TopBar/topBar'
export default class RequestDetailsComponent extends Component {
showBreadcrumb: boolean;
breadcrumbs: { title: string; navigate: string; state: boolean; }[];
constructor(props: any) {
super(props)
this.showBreadcrumb = true;
this.breadcrumbs = [
{ title: 'Dashboard', navigate: 'dashboard', state: true },
{ title: 'Requests', navigate: 'requestList', state: true },
{ title: 'Request Details', navigate: '', state: false }]
}
render() {
return (
<div>
<TopBarComponent showBreadcrumb={this.showBreadcrumb} breadcrumbs={this.breadcrumbs}/>
</div>
);
}
}
Child component -- TopBar component
import React, { Component } from "react";
import { Breadcrumb, BreadcrumbItem } from 'carbon-components-react'
export default class TopBarComponent extends Component {
showBreadcrumb:boolean;
constructor(props:any){
super(props);
this.showBreadcrumb = props.showBreadcrumb
}
render() {
let breadcrumbClass = 'dte-breadcrumbs dte-breadcrumbs--with-layout';
if(this.showBreadcrumb){
return (
<div className={breadcrumbClass}>
<div className="dte-page-container">
<div className="container-fluid">
<Breadcrumb >
<BreadcrumbItem>
Breadcrumb 1
</BreadcrumbItem>
</Breadcrumb>
</div>
</div>
</div>
);
}
return null;
}
}
I want to pass 'showBreadcrumb' and 'breadcrumbs' array to topBar component from Requestdetails component. but unable to do it in react-redux.
The above approach i used to follow in react but now i'm trying this react-redux., but failed to pass.
Please advise how i can pass this.
Assuming you have your redux store and provider setup and configured correctly, the way to connect UI components to your redux store, believe it or not, is with react-redux's connect HOC.
import React, { Component } from "react";
import { connect } from 'react-redux'; // import the connect HOC
import { Breadcrumb, BreadcrumbItem } from "carbon-components-react";
class TopBarComponent extends Component {
render() {
let breadcrumbClass = "dte-breadcrumbs dte-breadcrumbs--with-layout";
if (this.props.showBreadcrumb) {
return (
<div className={breadcrumbClass}>
<div className="dte-page-container">
<div className="container-fluid">
<Breadcrumb>
<BreadcrumbItem>
Breadcrumb 1
</BreadcrumbItem>
</Breadcrumb>
</div>
</div>
</div>
);
}
return null;
}
}
// define a function that maps your redux state to props
const mapStateToProps = state => ({
breadcrumbs: state.breadcrumbs, // these should match how your reducers define your state shape
showBreadcrumb: state.showBreadcrumb,
});
// export the connected component
export default connect(mapStateToProps)(TopBarComponent);
I am trying to setup my first react/redux/rails app. I am using react_on_rails gem to pass in my current_user and gyms props.
Everything appears to work ok so far except my console shows error:
<Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/reactjs/react-redux/releases/tag/v2.0.0 for the migration instructions.
Googling gives me hints that this can happen if you try to create a store within a render method, which causes store to get recreated. I don't see that issue here. Where am I going wrong?
//App.js
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../store/gymStore';
import Gym from '../components/Gym';
const App = props => (
<Provider store={configureStore(props)}>
<Gym />
</Provider>
);
export default App;
../store/gymStore.jsx
//the store creation.
/*
// my original way
import { createStore } from 'redux';
import gymReducer from '../reducers/';
const configureStore = railsProps => createStore(gymReducer, railsProps);
export default configureStore;
*/
/* possible fix: https://github.com/reactjs/react-redux/releases/tag/v2.0.0 */
/* but adding below does not resolve error */
import { createStore } from 'redux';
import rootReducer from '../reducers/index';
export default function configureStore(railsProps) {
const store = createStore(rootReducer, railsProps);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept(() => {
const nextRootReducer = require('../reducers').default;
store.replaceReducer(nextRootReducer);
});
}
return store;
}
I am not sure my rendered component is necessary but in case it is:
//compenents/Gym.jsx
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import LeftMenu from './LeftMenu';
class Gym extends React.Component {
static propTypes = {
//name: PropTypes.string.isRequired // this is passed from the Rails view
};
/**
* #param props - Comes from your rails view.
*/
constructor(props) {
super(props);
this.state = {
current_user: this.props.current_user,
gyms: JSON.parse(this.props.gyms),
active_gym: 1, //JSON.parse(this.props.gyms)[0],
name: 'sean',
title: 'Gym Overview'
};
}
updateName = name => {
this.setState({ name });
};
isLoggedIn = () => {
if (this.state.current_user.id != '0') {
return <span className="text-success"> Logged In!</span>;
} else {
return <span className="text-danger"> Must Log In</span>;
}
};
isActive = id => {
if (this.state.active_gym == id) {
return 'text-success';
}
};
render() {
return (
<div className="content">
<h2 className="content-header">{this.state.title}</h2>
{LeftMenu()}
{this.state.current_user.id != '0' ? <span>Welcome </span> : ''}
{this.state.current_user.first_name}
<h3 className="content-header">Your Gyms</h3>
<ul>
{this.state.gyms.map((gym, key) => (
<li key={key} className={this.isActive(gym.id)}>
{gym.name}
</li>
))}
</ul>
{this.isLoggedIn()}
<hr />
{/*
<form>
<label htmlFor="name">Say hello to:</label>
<input
id="name"
type="text"
value={this.state.name}
onChange={e => this.updateName(e.target.value)}
/>
</form>
*/}
</div>
);
}
}
function mapStateToProps(state) {
return {
current_user: state.current_user,
gyms: state.gyms,
active_gym: state.active_gym
};
}
export default connect(mapStateToProps)(Gym);
Is there a performance difference in React between 1, 2 and 3?
1.
class App extends Component {
renderHeader = () => <h1>Hello</h1>;
render() {
return <div>
{this.renderHeader()}
</div>;
}
}
2.
class App extends Component {
render() {
return <div>
<h1>Hello</h1>
</div>;
}
}
3.
class App extends Component {
render() {
return <div>
<Header />
</div>;
}
}
class Header extends Component {
render() {
return <h1>Hello</h1>;
}
}
I'm new in React Native and trying create my first app. So I have a question:
I got 2 screens (using react-navigation). At first screen there is a render of app logo with spinner(from native-base) and fetch to the server at the same time. And I need to navigate to another screen only when fetch is over and responce is handled. Please help me find my mistakes!
index.ios.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,TouchableHighlight
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import LoadingScreen from './src/screens/LoadingScreen.js';
import MainContainer from './src/screens/MainContainer.js';
export default class Calculator2 extends Component {
render() {
return (
<LoadingScreen/>
);
}
}
const AppNavigator = StackNavigator({
Loading: {
screen: LoadingScreen
},
Main: {
screen: MainContainer
}
});
AppRegistry.registerComponent('Calculator2', () => Calculator2);
LoadingScreen.js:
import React, { Component } from 'react';
import {
AsyncStorage,
AppRegistry,NetInfo,
Text,Image,View
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import AppNavigator from '../../index.ios.js';
import { Container, Header, Content, Spinner } from 'native-base';
export default class LoadingScreen extends Component {
static navigationOptions = {
title: 'Loading',
};
constructor(props){
super(props);
}
componentDidMount(){
const {navigate} = this.props.navigation;
fetch('url').then( (response) => {navigate('Main')});
}
render() {
return(
<View>
App logo with spinner
</View>
);
}
}
MainContainer.js
import React, { Component } from 'react';
import {
AppRegistry,Alert,NetInfo,
StyleSheet,
Text,
View,ActivityIndicator,
TextInput,TouchableHighlight
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import AppNavigator from '../../index.ios.js';
export default class MainContainer extends Component {
static navigationOptions = {
title: 'Main',
};
render() {
return (
<View style={{flexDirection: 'column'}}>
...
</View>
);
}
}
And all I got is an error "Cannot read property 'navigate' of undefined" at LoadingScreen.componentDidMount
UPD
actually my fetch should be a function getting responce and handling it, and it should wait till handling is done:
async function getData(){
var response = await fetch('url', {
method: 'GET'
});
storage = await response.json(); // storage for response
regions = Object.keys(storage); // an array of regions names
console.log(storage, Object.keys(storage));
};
You need to register AppNavigator component instead of Calculator2
AppRegistry.registerComponent('Calculator2', () => AppNavigator);
Just update your LoadingScreen.js's componentDidMount function as following:
componentDidMount() {
var self = this;
fetch('url').then( (response) => {
self.props.navigation.navigate('Main')
});
}
Hello i have this code
import React from 'react'
import Link from 'react-router/lib/Link'
import { connect } from "react-redux"
import { load } from '../../actions/customerActions'
import List from './list';
import MdAdd from 'react-icons/lib/md/add'
#connect(store => {
return {
customers: store.customer.customers
}
})
export default class Customer extends React.Component {
componentDidMount() {
this.props.dispatch(load({location:localStorage.getItem('locationb')}));
}
render() {
const { customers } = this.props;
const tea = customers.customers && customers.customers.map(customer => <List key={customer.profile} customer={customer} />) || [];
return(
<div class="container">
{ customers.customers ?
<div class="columns is-multiline mb-100">
{ tea }
</div>
: 'Não exitem Clientes'}
<Link to="/customer/create" class="button is-info btn-rounded" title="Novo"><MdAdd /></Link>
</div>
)
}
}
But i only have access to customers in render passing this props.
How can i pass customer to a state variable in component did mount or else ?
i mean customers const { customers } = this.props; how i make like this.setState({customers: customers}) Having in the beginning this.state(customers: [])
YOu can use
componentWillReceiveProps(newProps){
console.log(newProps.customers.customers)
this.setState({customers: newProps.customers.customers})
}
it works for me
thanks
Carlos Vieira