How can I wait for init config to complete? - reactjs

I've this code
class ConnectedApp extends Component {
constructor(props) {
super();
props.initConfig(); // the ajax call that populate the user settings
}
render() {
return (
<I18nextProvider i18n={i18n}>
<Router>
<div className="App" style={appStyle}>
<Head/>
<div className="Container">
<Container/>
</div>
<Foot/>
<Loading/>
<ToastContainer position="bottom-right" />
</div>
</Router>
</I18nextProvider>
);
}
}
Now the problem is that the initconfig is an ajax function in middleware. Before rendering the app for logged user I need to wait that the function has finished. Anyone have some suggestion?
Actually the app works nut on first login give an error and that error is resolved by manual refresh.

You'll need to change a few things here– Firstly you will need some way to indicate loading. This can be done in it's simplest form using a boolean either in your global or local state. You should also move your AJAX call method into the appropriate component lifecycle method componentDidMount.
You want it in your componentDidMount to ensure the component is mounted and ready to receive props or state changes.
class ConnectedApp extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.initConfig();
}
render() {
if (this.props.loading === true) {
return null // this will render nothing until loading is `false`
}
return (
<I18nextProvider i18n={i18n}>
<Router>
<div className="App" style={appStyle}>
<Head/>
<div className="Container">
<Container/>
</div>
<Foot/>
<Loading/>
<ToastContainer position="bottom-right" />
</div>
</Router>
</I18nextProvider>
);
}
}
In your redux state you would want to set a property for the loading state. When you start the request, you would set loading to true, when it is successful set it to false. If it fails, you would need a more expandable solution to account for that other than a simple 'loading' boolean.
Also, if you haven't checked out the new React Hooks API, this is what your component would look like using that.
import React, { useEffect } from "react";
const ConnectedApp = ({ initConfig, loading }) => {
useEffect(() => {
initConfig() // this will only get called when the component mounts. Same as `componentDidMount`
}, [])
if (loading === true) {
return null // this will render nothing until loading is `false`
}
return (
<I18nextProvider i18n={i18n}>
<Router>
<div className="App" style={appStyle}>
<Head/>
<div className="Container">
<Container/>
</div>
<Foot/>
<Loading/>
<ToastContainer position="bottom-right" />
</div>
</Router>
</I18nextProvider>
);
}

Related

React - Call function from non-parent component with state from separate component

I'm attempting to call a function from an AppBar with the state from a child component, like so
// App.js
<BrowserRouter>
<Nav />
<Routes>
<Route exact path={"/"} element={<MyComponent/>}/>
<Routes>
</BrowserRouter>
//Nav.js
function Nav() {
return (
<div>
<h1>Hello World</h1>
<button onClick={logChildState}>Get State</button>
</div>
)
}
// MyComponent.js
function MyComponent() {
const [someState, setSomeState] = useState({
Some state values....
})
return (
<div>
<input />
...more components...
</div>
)
}
logChildState() == "Some state values...."
The goal is to have the AppBar have a button with a function call that captures the state of MyComponent. As this is a simplified example, I will just say that the state should exist in the child, and it's not possible to hoist the state to App.js - because of this, I don't see a way to accomlish what I'm looking for easily, I've looked at possibly achieving this using context or an observable but it would be quite messy.
I'm wondering what the best way to tackle this kind of issue would be, or if my best choice would just be to have the "button" in Nav.js in the MyComponent.js.
Thanks
You can add the function as a prop like this:
//Nav.js
function Nav({logChildState}) {
return (
<div>
<h1>Hello World</h1>
<button onClick={() => logChildState('send this message')}>Get State</button>
</div>
)
}
And in your app Component you can simply take it as a prop like this:
<Nav logChildState = {logChildState}/>
and if you want to print the message comming from Nav component simply do this in App.js
const logChildState = (message) => {
console.log(message);
}
Hope that helps!

React Component, with a nested component access this.props

I am stuck with a small challenge, and that is the how to have a sub-component access things like this.props (specifically looking for this.props.history). My code is essentially;
// app.js, setup a router...
return (
<Router>
<Route path="/componenta" component={ComponentA}/>
</Router>
);
// Component A has access to this.props
class ComponentA extends Component {
componentDidMount() {
console.log('The props are ', this.props);
}
render() {
return (
<div>
<h1>Hello from Component A</h1>
<ComponentB/>
</div>
);
}
}
// ComponentB does not have access to this.props,
// and I know it is because it is a sub-component here.
class ComponentB extends Component {
componentDidMount() {
console.log('The props are ', this.props);
}
render() {
return (
<div>
<h1>Hello from Component B</h1>
</div>
);
}
}
I feel like it is something simple I am missing, any suggestions?
Thanks.
React router automatically passes ComponentA props that belong to react router. That's why you see them in ComponentA. It will provide match, location, and history (docs).
You can think of Route as being something like this:
class Route extends React.Component {
render() {
if (props.path == *actual_url*) {
return React.createElement(props.component, {history, match, location});
// Which in your case results in
// <ComponentA history={history} location={location} match={match} />
} else {
return null;
}
}
}
Note: This is a very simplified illustration. Actual Route class is here and is a little more complicated.
So you have to manage those props from there. To access them in children components, you will need to pass the props you want explicitly like this:
<ComponentB
history={this.props.history}
location={this.props.location} // If needed
match={this.props.match} // If needed
/>
Or if you know you want to pass all props to the nested component, you could use this shorthand:
<ComponentB {...this.props} /> // will result in same props as above example
Personally I prefer to be explicit and use the first example, as just doing {...this.props} tends to lead to components receiving way more props than they need. But that much is up to you.
Change your line where you use ComponentB to include history if you want to use it inside ComponentB:
<ComponentB history={this.props.history} />
You're failing to pass props from ComponentA to ComponentB.
return (
<div>
<h1>Hello from Component A</h1>
<ComponentB passedProps={this.props} />
</div>
);
welcome to SO, i see that you are not passing any prop to the ComponentB so you have to do something like this;
<ComponentB history={this.props.history}/>
And then you will be able to use the history on your ComponentB

Adding a Link as a child of a Router with ReactDOM.render yields "You should not use <Link> outside a <Router>"

I am looking for a way to use ReactDOM.render to create a Link within a react router. The setup more or less looks like this:
const router = (
<div>
<Router>
<Route path="/map" component={Map}/>
</Router>
</div>
);
The relevant parts of Map.jsx look like this:
const MapPopup = () => {
return (
<Link to={`/map/add`} />
)
}
class Map extends React.Component {
componentDidMount() {
this.map = L.map('map')
//...stuff...
this.map.on('contextmenu', event => {
popup
.setLatLng(event.latlng)
.addTo(this.map)
.setContent(
ReactDOM.render(
MapPopup(),
document.querySelector('.leaflet-popup-content')
)[0]
)
.openOn(this.map)
})
}
render() {
return (
<React.Fragment>
<div id="map" />
</React.Fragment>
)
}
}
I am basically trying to add a Link to the map popup provided by leaflet (I can't use react-leaflet for this project). If I however return the MapPopup directly in the render function it works (obviously not in the popup but the Link does work this way).
<React.Fragment>
<div id="map" />
<MapPopup />
</React.Fragment>
Does anyone have an idea how I can tackle this rather unusual problem?
I am using "react-router-dom": "4.3.1".
This is the expected error since <Link> component expects ancestor component to be of router type (<BrowserRouter>, <MemoryRouter>, <Router> ... ), refer this thread for a more details.
For your scenario to circumvent this limitation ReactDOM.createPortal could be utilized instead of ReactDOM.render:
<Route
path="/popup"
render={() => (
<Popup>
<div>
Some content goes here
<Link to="/map"> Back to map</Link>
</div>
</Popup>
)}
/>
where
class Popup extends React.Component {
render() {
return ReactDOM.createPortal(
this.props.children,
document.querySelector("#link-render-div")
);
}
}
and
Here is a demo for your reference

My component is creating TypeError: Cannot read property 'click' of null

This problem is related with my Buy_Item Component. The Urban Outfitter logo at the top left is supposed to bring you back to the home page. It works completely fine with my other components, except this one. When I click it gives me:
class App extends Component {
render() {
return (
<BrowserRouter>
<div className="App">
<Header/>
<Route exact path="/" render = {() => <Featured/> } />
<Route path="/items-available" render = {() => <Items_Available item_info={<Item_Info/>}/> } />
<Route path="/buy-item" render = {() => <Buy_Item buy_item_info={<Buy_Item_Info/>}
item_info={<Item_Info/>}/> } />
<Footer/>
</div>
</BrowserRouter>
);
}
}
export default App;
Here's what the "Urban Outfitter" logo does in my Header Component:
<div id="nav_logo_container">
<Link to="/">
<picture>
<source media="(min-width:768px)" srcset={uo_logo} />
<source srcset={uo_logo_smaller_screen} />
<img id="nav_logo" src={uo_logo} alt="Urban Outfitters Logo" />
</picture>
</Link>
</div>
Here's my Github repo, if it helps: https://github.com/mattfrancis888/project_2/tree/item_info/src
You have it all wrong in your Buy_Item component
Never call setState inside the render() method as it could cause an infinite loop. This is because calling setState will always lead to a re-render unless shouldComponentUpdate returns false.
Try this...
const imgDic = {
0: item_1,
1: item_1_alt,
2: item_1_alt2,
3: item_1_alt3,
4: item_1_alt4,
5: item_1_alt5
};
class Buy_Item extends React.Component {
constructor(props) {
this.state = {
radioStatus: null,
currentImg: item_1
};
this.handleRadioClick = this.handleRadioClick.bind(this);
}
handleRadioClick(radioId) {
this.setState({
radioStatus: radioId,
currentImg: imgDic[radioId]
});
}
render() {
// the rest of render code goes here...
}
}

ReactJS, React-Router: Calling parent function

I am working on a React App, trying to call a parent method from a child component, some code of the parent component below:
class NavigationBar extends Component {
constructor(props){
super(props);
this.state={isLoggedIn: false};
}
updateLoginState(){
alert("Login from NavigationBar");
}
GetBar() {
//const isLoggedIn = this.props.isLoggedIn;
if (false){ //isLoggedIn
return this.UserNavBar();
}
return this.StrangerNavBar();
}
StrangerNavBar(){
return (
<div>
<HashRouter>
<div>
{/* ... */}
<div className="content">
<Route exact path="/LoginCC" loginUpdate={this.updateLoginState} component={LoginCC} />
</div>
</div>
</HashRouter>
</div>
);
}
render() {
return (
this.GetBar()
);
}
}
export default NavigationBar;
This component is supposed to redirect the user to different content pages based on whether or not he is logged in, using a Router. If a button is clicked in LoginCC.js the method updateLoginState should be invoked which just displays a message for now. The child content page LoginCC.js looks as follows:
class LoginCC extends Component {
constructor(props){
super(props);
this.state = {isLoggedIn: false};
}
render() {
return (
<div>
<HashRouter>
{/* ... */}
<Button variant="primary" size="lg" block onClick={this.props.loginUpdate}>
Log in
</Button>
{/* ... */}
</HashRouter>
</div>
);
}
}
export default LoginCC;
I passed the method reference as a prop to LoginCC when rendering this component using the Router, so a message should pop up if I press the button, but nothing happens.
Am I passing the prop incorrectly or something else I've missed? I'm new to React so any help is appreciated.
Route doesn't pass any custom props to components. You should use other method to pass functions.
One of solutions is:
<Route exact path="/LoginCC" render={
props => <LoginCC {...props} loginUpdate={this.updateLoginState}/>
} />
Note that updateLoginState will not get this when called. You should either bind it or declare it as an arrow function to get the correct this.
Also check the Context documentation.

Resources