Reputation: 459
I have a component Careers.jsx
import React from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import qs from 'query-string';
import Filters from './Filters'
const CareersList = ({ location, careers }) => {
return (
<div className="careers_listing">
{location.search}
{ careers.map((career) =>
<div key={career.id}>
{career.title}
</div>
)}
</div>
);
}
class Careers extends React.Component {
componentDidMount () {
this.getCareers();
}
getCareers() {
axios.get(this.props.url)
.then(res => {
const careers = res.data.careers;
this.setState({ careers });
});
}
constructor (props) {
super(props);
this.state = {
careers: []
}
}
render () {
return (
<Router>
<div className="rct">
<Filters filters={this.props.filters} path={this.props.path} />
<div className="rct_listing">
<Route path={decodeURIComponent(this.props.path)} render={props => (
<CareersList careers={this.state.careers} {...props} />
)}/>
</div>
</div>
</Router>
);
}
}
export default Careers
I want to filter careers list by query or hash params, like: /careers?type=public. I can filter by .find()
, but I want to reload ajax data with special params and rerender list.
Main problem: I can't access to getCareers()
from CareersList. How I can reload Career state from CareersList component?
Upvotes: 0
Views: 539
Reputation: 3487
You could pass the method as a prop to CareersList for example:
import React from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import qs from 'query-string';
import Filters from './Filters'
const CareersList = ({ location, careers }) => {
// You can call `this.props.getCareers()` here
return (
<div className="careers_listing">
{location.search}
{ careers.map((career) =>
<div key={career.id}>
{career.title}
</div>
)}
</div>
);
}
class Careers extends React.Component {
componentDidMount () {
this.getCareers();
}
getCareers() {
axios.get(this.props.url)
.then(res => {
const careers = res.data.careers;
this.setState({ careers });
});
}
constructor (props) {
super(props);
this.state = {
careers: []
}
}
render () {
return (
<Router>
<div className="rct">
<Filters filters={this.props.filters} path={this.props.path} />
<div className="rct_listing">
<Route path={decodeURIComponent(this.props.path)} render={props => (
<CareersList getCareers={this.getCareers} careers={this.state.careers} {...props} />
)}/>
</div>
</div>
</Router>
);
}
}
export default Careers
Upvotes: 1