Skip to content

Instantly share code, notes, and snippets.

@kvendrik
Created July 9, 2018 16:07
Show Gist options
  • Save kvendrik/fc859b96ecc6fb9faf5c28cabcd7f254 to your computer and use it in GitHub Desktop.
Save kvendrik/fc859b96ecc6fb9faf5c28cabcd7f254 to your computer and use it in GitHub Desktop.
TypeScript example: passing props into a Route.
import * as React from 'react';
import {render} from 'react-dom';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import './styles/globals/all.scss';
import StockPhotoSearch from './components/StockPhotoSearch';
render((
<BrowserRouter>
<Switch>
<Route path="/:query" component={StockPhotoSearch} exact={true} />
</Switch>
</BrowserRouter>
), document.getElementById('app'));
import * as React from 'react';
import {RouteComponentProps} from 'react-router-dom';
import {Bind, Debounce} from 'lodash-decorators';
import SearchBar from 'Components/SearchBar';
import ImagePreview from 'Components/ImagePreview';
import * as styles from './StockPhotoSearch.scss';
type Props = {};
type ComposedProps = Props & RouteComponentProps<{
query: string;
}>;
interface Image {
id: string;
url: string;
}
export default class StockPhotoSearch extends React.Component<ComposedProps, {
searching: boolean;
images: Image[];
}> {
constructor(props: ComposedProps) {
super(props);
this.state = {
searching: false,
images: [],
};
}
@Debounce(300)
doSearch(query: string) {
this.setState({searching: true, images: []});
fetch(`https://api.unsplash.com/search/photos?query=${encodeURI(query)}&client_id=4e0551efb2e3bc6fadad1b98a0f39efa8b462f031ce5460e63e9c3571bca347f&per_page=10`)
.then((res) => res.json())
.then(({results}) => {
const images = results.map(({id, urls: {thumb}}: any) => ({id, url: thumb}));
this.setState({images, searching: false});
});
}
@Bind()
onInputChange({target}: React.ChangeEvent<HTMLInputElement>) {
const query = (target as HTMLInputElement).value;
this.doSearch(query);
}
render() {
console.log(this.props.match.params.query);
const {images, searching} = this.state;
return (
<section className={styles.StockPhotoSearch}>
<SearchBar onChange={this.onInputChange} />
<div>
{searching && 'Searching...'}
{images.length < 1 && !searching && 'No results.'}
{images.map(({id, url}) => <ImagePreview key={id} src={url} />)}
</div>
</section>
);
}
}
@estebanarivasv
Copy link

THANKS A LOT!!! ๐Ÿ™Œ๐Ÿผ๐Ÿ™Œ๐Ÿผ๐Ÿ™Œ๐Ÿผ๐Ÿ™Œ๐Ÿผ

@atilara
Copy link

atilara commented Jun 28, 2021

You saved me! Thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment