searchChange is not defined no-undef - javascript

SearchBox.js File is:
import React from 'react';
const SearchBox = ({ searchfield, searchChanger}) => {
return (
<div className='pa2'>
<input
className='pa3 b--green bg-light-blue'
type='search'
placeholder='search robots'
onChange={searchChange}
/>
</div>
);
}
export default SearchBox;
App.js File is:
import React, { Component } from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import { robots } from './robots';
import './App.css';
class App extends Component {
constructor() {
super()
this.state = {
robots: robots,
searchfield:''
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {this.setState({ robots: robots})});
}
onSearchChange = (event) => {
this.setState({ searchfield: event.target.value })
}
render() {
const filteredRobots = this.state.robots.filter(robots => {
return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
if (robots.length ===0) {
return <h1>Loading</h1>
}
else {
return (
<div className='tc'>
<h1 className='f1'>RoboFriends</h1>
<SearchBox searchChange={this.onSearchChange}/>
<CardList robots={filteredRobots} />
</div>
);
}
}
}
export default App;
I was able to get rid of this error just by changing the order of import in App.js file, but later on its showing this error no matter what i do?
please help in case I have any typing issue, if no then what is the problem

Your SearchBox should be:
const SearchBox = ({ searchfield, searchChange}) => {
return (
<div className='pa2'>
<input
className='pa3 b--green bg-light-blue'
type='search'
placeholder='search robots'
onChange={searchChange}
/>
</div>
);
}
export default SearchBox;
In your props there was searchChanger which is incorrect.

Related

I doing a course of React and i have a error when i try add a functionality to my course project

This is the error
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of PhotoCardWithQuery.
This is my code
PhotoCardWithQuery.js
import React from 'react'
import { PhotoCard } from '../components/PhotoCard'
import { gql } from 'apollo-boost'
import { Query } from '#apollo/client'
const GET_SINGLE_PHOTO = gql`
query getSinglePhoto($id:ID!) {
photo(id:$id) {
id
categoryId
src
likes
userId
liked
}
}
`
const renderProp = ({ loading, error, data }) => {
if (loading) return <p>loading...</p>
if (error) return <p>Error!</p>
const { photo = {} } = data
return <PhotoCard {...photo} />
}
export const PhotoCardWithQuery = ({ id }) => (
<Query query={GET_SINGLE_PHOTO} variables={{ id }}>
{renderProp}
</Query>
)
Detail.js
import React from 'react'
import { PhotoCardWithQuery } from '../container/PhotoCardWithQuery'
export const Detail = ({ detailId }) => (
<PhotoCardWithQuery id={detailId} />
)
App.js
import React from 'react'
import { GlobalStyle } from './styles/GlobalStyles'
import { Logo } from './components/Logo'
import { Home } from './pages/Home'
import { Router } from '#reach/router'
import { Detail } from './pages/Detail'
export const App = () => {
return (
<div>
<GlobalStyle />
<Logo />
<Router>
<Home path='/' />
<Home path='/pet/:id' />
<Detail path='/detail/:detailId' />
</Router>
</div>
)
}
PhotoCard.js
import React, { Fragment } from 'react'
import { Article, ImgWrapper, Img } from './styles'
import { useLocalStorage } from '../../hooks/useLocalStorage'
import { useNearScreen } from '../../hooks/useNearScreen'
import { FavButton } from '../FavButton/index.js'
import { ToggleLikeMutation } from '../../container/ToggleLikeMutation'
import { Link } from '#reach/router'
const DEFAULT_IMAGE = 'https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60'
export const PhotoCard = ({
id, likes = 0,
src = DEFAULT_IMAGE
}) => {
const [show, element] = useNearScreen()
const key = `like-${id}`
const [liked, setLiked] = useLocalStorage(key, false)
return (
<Article ref={element}>
{
show &&
<>
<Link to={`/detail/${id}`}>
<ImgWrapper>
<Img src={src} />
</ImgWrapper>
</Link>
<ToggleLikeMutation>
{
(toggleLike) => {
const handleFavClick = () => {
!liked && toggleLike({
variables: {
input: { id }
}
})
setLiked(!liked)
}
return (
<FavButton
liked={liked} likes={likes} onClick={handleFavClick}
/>
)
}
}
</ToggleLikeMutation>
</>
}
</Article>
)
}

React Test cases with Jest and Enzyme

I am new to writing test cases for React. Can someone tell me how to proceed with writing test cases for this file and how to finish code coverage.
How do i test mapDispatchToProps, componentDidMount or handleClick functions below. Can someone explain me how to proceed with steps to achieve test cases.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import DOMPurify from 'dompurify'
import escape from 'escape-html'
import Message from 'wf-dbd-react-ui/es/Message'
import ContentEventWrapper from 'wf-dbd-react-ui/es/ContentEventWrapper'
import { unescapeHtml } from 'wf-dbd-react-ui/es/lib'
import { requestNavigation } from 'wf-dbd-react-ui/es/actions'
import NavigationItemRecord from 'wf-dbd-react-ui/es/lib/records/NavigationItemRecord'
import ScrollToTopOnMount from 'wf-dbd-react-ui/es/ScrollToTopOnMount'
class MessageDisplayWithSpecialCharacters extends Component { //NOSONAR
constructor(props) {
super(props)
this.elementRef = null
}
componentDidMount() {
if (this.props.focusOnMount) {
if (this.elementRef) {
this.elementRef.blur() //needed to reset focus in iOS
this.elementRef.focus()
setTimeout(() => { this.elementRef.focus() }, 100) //timeout needed for Android
}
}
}
setElementRef = element => {
this.elementRef = element
}
handleClick = ({ target }) => {
const { requestNavigation } = this.props
if (target.hasAttribute('data-cui-link')) {
const navigationItem = new NavigationItemRecord({
samlNavigation: true,
displayType: 'saml',
navigationUrl: target.getAttribute('data-cui-link')
})
requestNavigation(navigationItem)
}
}
render() {
const { messages, className } = this.props
return (
<div className={className} tabIndex="-1" ref={this.setElementRef}>
<ScrollToTopOnMount />
{messages.map((message, index) => {
const purifiedContent = { __html: DOMPurify.sanitize(unescapeHtml(JSON.parse(`"${escape(window.decodeURIComponent(message.get('message')))}"`))) }
return (
<ContentEventWrapper handleContentClick={this.handleClick} key={index}>
<Message announce={true} level={message.get('level')}>
<p dangerouslySetInnerHTML={purifiedContent} />
</Message>
</ContentEventWrapper>
)
})}
</div>
)
}
}
MessageDisplayWithSpecialCharacters.propTypes = {
messages: PropTypes.array,
className: PropTypes.string,
focusOnMount: PropTypes.bool,
requestNavigation: PropTypes.func
}
const mapDispatchToProps = dispatch => ({
requestNavigation: navigationItem => dispatch(requestNavigation(navigationItem))
})
export default connect(null, mapDispatchToProps)(MessageDisplayWithSpecialCharacters)
Any help/ advice is appreciated for a novice like me.

object can't get method or property 'getCars'

i'm working on react-redux intermidiate..but i don't know what's going wrong
on this project
hera i have creacted the searchbar for getting car details..and the file is created as 'search.js'...you can see here..
search.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getCars } from '../actions';
import { bindActionCreators } from 'redux';
class Search extends Component{
constructor(props){
super(props);
this.state = {
keyword:''
}
}
searchCars = (event) => {
event.preventDefault();
this.props.getCars(this.state.keyword)
}
handleChange = (event) => {
this.setState({
keyword:event.target.value
})
}
componentDidMount(){
console.log(this.state);
}
render(){
return(
<div className="main_search">
<form onSubmit={this.searchCars}>
<input type="text" value={this.state.keyword} onChange = {this.handleChange} />
</form>
</div>
)
}
}
// mapStateToProps
// mapDispatchToProps
function mapDispatchToProps(dispatch){
return bindActionCreators({getCars}, dispatch)
}
export default connect(null,mapDispatchToProps)(Search);
and i think error comes from here about getCars..which is described below as s 'index.js'...you can see here
index.js
const URL_ROOT = 'http://localhost:3004'
export default function getCars(keywords){
const request = fetch(`${URL_ROOT}/carsIndex?q=${keywords}`,
{method:'GET'})
.then(response => response.json())
return{
type:'SEARCH_CARS',
payload:request
}
}
and the error looks like this..
and error showing in bundle.js file
so try to fix it and help me...
Please change your mapDispatchToProps method as
const mapDispatchToProps = (dispatch)=> (
bindActionCreators(getCars, dispatch)
)

ReactJS - how to update data for an attribute in props?

I have a list of posts and for every post, there's is a button that will display a modal window with a confirmation if the user really wants to delete the respective post.
When the user confirms, data are send to backend, there's delete the respective post and back to ReactJS is returned a set of all posts. But when try to update the list of posts on the front-end, I get this error:
Posts.jsx:61 Uncaught (in promise) TypeError: _this2.props.posts is not a function
This error is raised on this line:
this.props.posts(res.data);
Home.jsx
import React from "react";
import Posts from './Posts';
import NewPost from './NewPost';
import axios from 'axios';
import Moment from 'react-moment';
import LoadModal from './LoadModal';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
loading: true
};
}
componentDidMount() {
axios.get('/posts')
.then(response => {
console.log('---');
console.log(response.data);
console.log('---');
this.setState({ posts: response.data, loading: false });
});
}
render() {
return (
<div>
<Posts posts={this.state.posts} loading={this.state.loading} />
</div>
)
}
}
export default Home
Posts.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import {Collapse} from 'react-collapse';
import classNames from "classnames";
import Dialog from 'react-bootstrap-dialog';
class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
activeIndex: null,
removePostBtn: 'Remove'
}
}
onClick(post_id) {
this.dialog.show({
title: 'Remove Post - #'+post_id,
body: 'Do you really want to remove this post?',
actions: [
Dialog.CancelAction(),
Dialog.DefaultAction(
this.state.removePostBtn,
() => {
this.setState({ removePostBtn: 'Removing...' }, () => {
axios.get('/remove_post/'+post_id, { post_id: post_id })
.then(res => {
this.props.posts(res.data); // here's the error
})
})
},
'btn-danger'
)
],
})
}
render () {
let content;
const { activeIndex } = this.state;
const Button = require('react-bootstrap').Button;
if (this.props.loading) {
content = 'Loading...';
} else {
content = this.props.posts.map((post, index) => {
return(
<li key={index}>
<div>
<span>{post.id}</span>
<span>{post.message}</span>
<Button onClick={() => this.onClick(post.id)}>Show alert</Button>
<Dialog ref={(el) => { this.dialog = el }} />
</div>
</li>
)
});
}
return (
<div>
<h1>Posts!</h1>
<div className="row">
<div className="col-md-6">
<ul>
{content}
</ul>
</div>
</div>
</div>
);
}
}
export default Posts
How do I properly update the props with posts?
You can't directly update any props. You need to create an update handler in the parent component that will update this.state.posts:
import React from "react";
import Posts from './Posts';
import NewPost from './NewPost';
import axios from 'axios';
import Moment from 'react-moment';
import LoadModal from './LoadModal';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
loading: true
};
}
componentDidMount() {
this.getPosts();
}
getPosts = () => {
axios.get('/posts')
.then(response => {
console.log('---');
console.log(response.data);
console.log('---');
this.setState({ posts: response.data, loading: false });
});
}
updatePosts = posts => {
this.setState({ posts });
}
render() {
return (
<div>
<Posts posts={this.state.posts} loading={this.state.loading} getPosts={this.getPosts} updatePosts={this.updatePosts} />
</div>
)
}
}
export default Home
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import {Collapse} from 'react-collapse';
import classNames from "classnames";
import Dialog from 'react-bootstrap-dialog';
class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
activeIndex: null,
removePostBtn: 'Remove'
}
}
onClick(post_id) {
this.dialog.show({
title: 'Remove Post - #'+post_id,
body: 'Do you really want to remove this post?',
actions: [
Dialog.CancelAction(),
Dialog.DefaultAction(
this.state.removePostBtn,
() => {
this.setState({ removePostBtn: 'Removing...' }, () => {
axios.get('/remove_post/'+post_id, { post_id: post_id })
.then(res => {
//this.props.posts(res.data); // here's the error
// Call parent function to re-retch posts
this.props.getPosts();
// Or direclty pass data to update the parent state
this.props.updatePosts(res.data);
})
})
},
'btn-danger'
)
],
})
}
render () {
let content;
const { activeIndex } = this.state;
const Button = require('react-bootstrap').Button;
if (this.props.loading) {
content = 'Loading...';
} else {
content = this.props.posts.map((post, index) => {
return(
<li key={index}>
<div>
<span>{post.id}</span>
<span>{post.message}</span>
<Button onClick={() => this.onClick(post.id)}>Show alert</Button>
<Dialog ref={(el) => { this.dialog = el }} />
</div>
</li>
)
});
}
return (
<div>
<h1>Posts!</h1>
<div className="row">
<div className="col-md-6">
<ul>
{content}
</ul>
</div>
</div>
</div>
);
}
}
export default Posts

Syntax error: Unexpected token, expected , (24:2)

So I'm getting this error message saying that I have a syntax error on line 24. Which is the onSearchChange line.
Please someone help me, I've been stuck on this problem for over a day now.
import React, { Component } from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import './App.css';
class App extends Component {
constructor() {
super()
this.state = {
robots: [],
searchfield: ''
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response=> {
return response.json();
})
.then(users => {
this.setState({ robots: users})
}
onSearchChange = (event) => {
this.setState({ searchfield: event.target.value })
}
render() {
const filteredRobots = this.state.robots.filter(robots =>{
return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
return (
<div className ='tc'>
<h1 className='f1'> RoboFriends</h1>
<SearchBox searchChange={this.onSearchChange}/>
<CardList robots={filteredRobots} />
</div>
);
}
}
export default App;
Your render function is inside componentDiDMount. Check for the opening and closing braces.

Categories

Resources