React-search basic example - reactjs

I'm trying to get react-search to work in my Meteor app. This is my main App.js in the imports folder:
import Search from 'react-search';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
...
class App extends Component {
...
render() {
let items = [
{ id: 0, value: 'ruby' },
{ id: 1, value: 'javascript' },
{ id: 2, value: 'lua' },
{ id: 3, value: 'go' },
{ id: 4, value: 'julia' }
]
console.log(items)
return (
<div class="">
<Search items={items} />
...
</div>
);
}
}
Once I insert the <Search items={items} /> my app stops working and I get the following console errors:
Any ideas?

I take a look on their source code: https://github.com/StevenIseki/react-search/blob/master/src/Search.js
import React, { Component, PropTypes } from 'react'
React had a break change where PropTypes is no longer inside the react package.
It's in prop-types package now. eg: import PropTypes from 'prop-types'
If you still want to use this package, you have to match the dependency in https://github.com/StevenIseki/react-search/blob/master/package.json
However, the implementation for this package isn't hard. So you highly recommend you create your own component based on their code if needed.
Does this help?

Related

React app failing to display list from objects. Getting this error: TypeError: Cannot read property '0' of undefined

I am doing a React course here and the starter files keep giving me this error:
TypeError: Cannot read property '0' of undefined
From this starter code:
import React from 'react'
import ReactDOM from 'react-dom'
const notes = [
{
id: 1,
content: 'HTML is easy',
date: '2019-05-30T17:30:31.098Z',
important: true
},
{
id: 2,
content: 'Browser can execute only Javascript',
date: '2019-05-30T18:39:34.091Z',
important: false
},
{
id: 3,
content: 'GET and POST are the most important methods of HTTP protocol',
date: '2019-05-30T19:20:14.298Z',
important: true
}
]
const App = (props) => {
const { notes } = props
return (
<div>
<h1>Notes</h1>
<ul>
<li>{notes[0].content}</li>
<li>{notes[1].content}</li>
<li>{notes[2].content}</li>
</ul>
</div>
)
}
ReactDOM.render(
<App notes={notes} />,
document.getElementById('root')
)
Above code shows:
Attempted import error: './App' does not contain a default export
(imported as 'App')
I tried amending by adding export default app and received:
TypeError: Cannot read property '0' of undefined
How can I solve this problem?
The code from link you are referring is the complete index.js file only.
If you want your code to be modular and want to separate out App component, in that case, you should do this,
index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import App from "./App"; //import your component (imported without { }, because App component exported as default)
const notes = [
{
id: 1,
content: 'HTML is easy',
date: '2019-05-30T17:30:31.098Z',
important: true
},
{
id: 2,
content: 'Browser can execute only Javascript',
date: '2019-05-30T18:39:34.091Z',
important: false
},
{
id: 3,
content: 'GET and POST are the most important methods of HTTP protocol',
date: '2019-05-30T19:20:14.298Z',
important: true
}
]
//Pass the props here
render(<App notes={notes}/>, document.getElementById('root'));
App.js
import React from 'react'
const App = (props) => {
const { notes } = props
return (
<div>
<h1>Notes</h1>
<ul>
<li>{notes[0].content}</li>
<li>{notes[1].content}</li>
<li>{notes[2].content}</li>
</ul>
</div>
)
}
export default App
Demo

React Redux Localize only returning first letter

I'm attempting to use react redux, but I'm facing an issue. The following code only renders the first letter, "T", rather than all of "Test". The Redux debugger shows all of "Test". How can this be?
Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { localizeReducer } from 'react-localize-redux';
import { combineReducers, createStore } from 'redux';
import { LocalizeProvider } from "react-localize-redux";
const store = createStore(
combineReducers({localize: localizeReducer})
);
ReactDOM.render(
<LocalizeProvider store={store}>
<App />
</LocalizeProvider>,
document.getElementById('root'));
App.js:
import React, { Component } from 'react';
import { Translate, withLocalize } from "react-localize-redux";
import { renderToStaticMarkup } from 'react-dom/server';
class App extends Component {
constructor(props) {
super(props);
this.props.initialize({
languages: [
{ name: "English", code: "en" }
],
options: { renderToStaticMarkup }
});
let english = {
abc: "Test"
}
this.props.addTranslation(english);
}
render() {
return <Translate id="abc" />;
}
}
export default withLocalize(App);
If you want to add a translation for just one language, you would use addTranslationForLanguage. This one uses the single language format:
let english = {
abc: "Test"
}
this.props.addTranslationForLanguage(english, 'en');
addTranslation should be used when using multiple languages. This api requires the data in all-language-format, so you would do something like this array for multiple languages:
let translations = {
abc: ["Test"]
}
this.props.addTranslationForLanguage(translations);

How Can I Share the Car interface between classes and add Type Checking To CarItem class?

I've made a simple example that highlights a few of the problems / not-understandings I'm having with TypeScript. I created a simple list of cars that reference a caritem detail view. Code is below and also on stackblitz here:
https://stackblitz.com/edit/react-ts-ocjswh
My Questions:
How do I get typechecking to work in CarItem.tsx? I've tried car: Car but that is not correct
What is the proper way to import react and react-dom? I tried import as with no success
I want to share my interface "Car" between index.tsx and CarItem.tsx so if I add another attribute, I don't have to add it to both places. Once I have a large number of interfaces in my project, what is best way to do this?
Index.tsx
import * as React from 'react';
import { render } from 'react-dom';
import CarItem from './CarItem';
interface Car
{
id: number,
model: string
}
interface Cars {
cars: Car[];
}
const App : React.FunctionComponent<Cars> = ({cars}) => {
const myCars = [{
id: 101, model: 'midget'
},{
id:102, model: 'spitfire'
},{
id: 103, model: 'tr6'
}]
return (
<ul>
{myCars.map(function(data){
return (
<CarItem car={data} />
)
}
)}
</ul>
);
}
render(<App />, document.getElementById('root'));
CarItem.tsx
import * as React from 'react';
interface Car
{
id: number,
model: string
}
export default ({car}) => {
return (
<li key={car.id}>...{car.model}</li>
)
}
There was a lot of problem with this code. I refactored it and try to fix it all.
The answers to your questions:
I fixed the type for CarItem
There is nothing wrong with the import, they works. The editor has some syntax highlight problem.
You can export and import the interfaces as well.
Here is the corrected files
index.tsx
import * as React from 'react';
import ReactDOM from 'react-dom';
import CarItem, {Car} from './CarItem';
const App : React.FunctionComponent = () => {
const myCars: Car[] = [{
id: 101, model: 'midget'
},{
id:102, model: 'spitfire'
},{
id: 103, model: 'tr6'
}]
return (
<ul>
{myCars.map(function(data){
return (
<CarItem key={data.id} car={data} />
)
}
)}
</ul>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
CarItem.tsx
import * as React from 'react';
export interface Car
{
id: number,
model: string
}
interface Props {
car: Car;
}
const CarItem: React.FunctionComponent<Props> = ({car}) => {
return (
<li>...{car.model}</li>
)
}
export default CarItem;
And the project: https://stackblitz.com/edit/react-ts-uknhel?file=index.tsx

Jest - Testing react with multiple HOC's. Material IU, react-router, mobX in Typescript

I'm trying to write unit tests for a project I have. To simplify the issues, I created a small sample project that shows the issues. You can pull it down from github here: Github Sample
Upon Shallow render, the error I get is:
TypeError: Cannot read property 'displayName' of undefined
at createStoreInjector (node_modules/mobx-react/index.js:585:46)
at node_modules/mobx-react/index.js:698:16
at Object.<anonymous> (src/Home/Home.tsx:21:76)
at Object.<anonymous> (src/Home/Home.test.tsx:17:189)
The issue I'm having is that I need to unit test components with multiple HOC's. There is one for styles from Material UI, one for react-router and two for mobX injection and observer. You can see the failing test in /src/Home in the file Home.test.tsx.
I can not figure out how to get a jest test to pass on this component. I also have the issue where I add to the Home Component. It also has the same multiple HOC's so that fails thing as well.
There must be a way to get these types of components tested, but I can't seem to get it to work. Any help would be awesome!
For those that don't want to pull the project, here is a summary of the component under test and the test itself.
Home.tsx
import withStyles, { WithStyles } from '#material-ui/core/styles/withStyles';
import classNames from 'classnames';
import { inject, observer } from 'mobx-react';
import * as React from 'react';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import logo from '../logo.svg';
import { HomeStore } from '../Stores/HomeStore';
import { styles } from './Home.Styles';
interface IProps extends RouteComponentProps<{}> {
homeStore?: HomeStore;
}
export default withStyles(styles)(
inject('homeStore')(
withRouter(
observer(
class Home extends React.Component<
IProps & RouteComponentProps<{}> & WithStyles<typeof styles>,
{}
> {
public render() {
const { classes } = this.props;
return (
<div className={classes.app}>
<header className={classes.appHeader}>
<img src={logo} className={classNames(classes.appLogo, classes.spin)} alt='logo' />
<h1 className={classes.appTitle}>Welcome to React</h1>
</header>
<p className={classes.appIntro}>
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
</div>
);
}
}))));
Home.test.tsx
import { shallow, ShallowWrapper } from 'enzyme';
import * as React from 'react';
import { MemoryRouter } from 'react-router';
import { HomeStore } from '../Stores/HomeStore';
import Home from './Home';
jest.mock('react-router-dom');
jest.mock('./Home.styles');
const homeStore = {} as HomeStore;
const props = {
homeStore: homeStore,
history: {},
location: {},
match: {},
staticContext: {}
};
describe('Order Tests', () => {
let homeWrapper: ShallowWrapper;
beforeEach(() => {
homeWrapper = shallow(<MemoryRouter><Home {...props} /></MemoryRouter>).first().shallow().first().shallow();
console.log(homeWrapper.debug());
});
it('passes a test', () => {
expect(true).toBe(true);
});
});

react-select component, not rendering

react: ^15.4.2,
react-select: ^1.0.0-rc.10,
Example.tsx
import * as React from 'react';
import Select from 'react-select';
// Be sure to include styles at some point, probably during your bootstrapping
import 'react-select/dist/react-select.css';
var Select = require('react-select');
var options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' }
];
function logChange(val) {
console.log("Selected: " + JSON.stringify(val));
}
export class Example extends React.Component<any, any> {
render() {
return (
<div>
<Select name="form-field-name" value="one" options={options} onChange={logChange}/>
</div>
);
}
}
No errors reported at compile time.
Get an error message when attempting to render it
React.createElement: type is invalid -- expected a string (for
built-in components) or a class/function (for composite components)
but got: object. Check the render method of Example.
in Example
Being this is my first react project I have no idea how to debug this. I do not see anything wrong with this code.
Here is my render out of main.tsx
(() => {
const container = document.querySelector('#container');
render( <Example />, container);
})();
Well, from the example above which is copy-pasted from react-select docs seems that everything is alright. The error says that you try to render something that is not being able to render (here it says it's some Object).
My bet is this line causes the error:
import Select from 'react-select';
are you sure you properly installed this package?
Try to usw curly brackets arround Select in your import statement:
import {Select} from...
If there are no "default" export defined, you have to use those curly bracets to define the component you want to use.
import * as React from 'react';
import Select from 'react-select';
// Be sure to include styles at some point, probably during your bootstrapping
import 'react-select/dist/react-select.css';
export class Example extends React.Component<any, any> {
var options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' }
];
function logChange(val) {
console.log("Selected: " + JSON.stringify(val));
}
render() {
return (
<div>
<Select name="form-field-name" value="one" options={options} onChange={logChange}/>
</div>
);
}
}
import React, { Component } from 'react';
import Select from 'react-select';
class App extends Component {
state = {options: [
{
value: '1', label: 'Option 1',
},
{
value: '2', label: 'Option 2',
}
]}
render(){
return (
<div>
<Select
className={"select-item"}
name="option name"
onChange={this.changeHandler}
options={this.state.options}
/>
</div>
)
}
}
Quick answer, this should work:
Demo: https://codesandbox.io/s/stupefied-vaughan-z4mkv?file=/src/Example.tsx
import * as React from "react";
import Select from "react-select";
// Be sure to include styles at some point, probably during your bootstrapping
import "react-select/dist/react-select.css";
var options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two" }
];
function logChange(val) {
console.log("Selected: " + JSON.stringify(val));
}
export default class Example extends React.Component<any, any> {
render() {
return (
<div>
<Select
name="form-field-name"
value="one"
options={options}
onChange={logChange}
/>
</div>
);
}
}
Reason for error:
Either use export default class Example extends React.Component<any, any> {, or in whichever file you are importing and using <Example />, import it as import { Example } from './path/to/file'. Not using the default export specifier or named import in the importing file is causing the error. Read imports / exports in js
Things to do:
Remove var Select = require('react-select');. This is the same as import Select from 'react-select';, just in a different import format (read about ESM and CommonJS to learn more). We should avoid importing components
Use import React from 'react' instead.

Resources