I've tried to fire an onchange function when my Textfield is filled, but i can't figure out why this function is never fired, even if React devtool plugin for Chrome actually trigger the changes, any advice ?
import React, {Component} from 'react';
import {Tracker} from 'meteor/tracker';
import {Meteor} from 'meteor/meteor';
import {Links} from '../api/links';
import LinkListItem from './LinkListItem';
import {Session} from 'meteor/session';
import SearchLink from './SearchLink';
import Fuse from 'fuse.js';
export default class LinkList extends Component {
constructor(props) {
super(props);
this.state = {
links: [],
inputValue: ''
};
}
componentDidMount() {
this.linksTracker = Tracker.autorun(() => {
Meteor.subscribe('links');
const links = Links.find({visible:
Session.get('showVisible')}).fetch();
this.setState({links});
});
}
componentWillUnmount() {
this.linksTracker.stop();
}
renderLinksListItems() {
if (this.state.links.length === 0) {
return (
<div>
<h2 className="link">{Session.get('showVisible') ? 'No links found' : 'No hidden links found'}</h2>
</div>
);
}
console.log(this.state.links);
return this.state.links.map((link) => {
const shortUrl = Meteor.absoluteUrl(link._id);
return <LinkListItem key={link._id} shortUrl={shortUrl} {...link}/>;
});
}
_onChange(e) {
if(e.target.value === "") {
return;
}
var fuse = new Fuse(this.state.links, { keys: ["url"]});
var result = fuse.search(e.target.value);
this.setState({
inputValue: e.target.value,
links: result
});
}
render() {
return (
<div>
<div>
<SearchLink onChange={this._onChange} value={this.state.inputValue}/>
</div>
<div>{this.renderLinksListItems()}</div>
</div>
);
}
}
My Textfield component :
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import TextField from 'material-ui/TextField';
const muiTheme = getMuiTheme({
palette: {
primary1Color: '#ef6c00'
}
})
const SearchLink = () => (
<MuiThemeProvider muiTheme={muiTheme}>
<TextField floatingLabelText="Search a Link" name="searchLink" fullWidth={true}/>
</MuiThemeProvider>
);
export default SearchLink;
Thank you for your help!
Do these changes:
1. Bind the method in Parent component LinkList, because you are using this.setState inside onChange method, if you don't bind it, it will throw the error, bind it like this:
<SearchLink onChange={this._onChange.bind(this)} value={this.state.inputValue}/>
or define the binding in constructor.
2. You are passing the event and value in props, so you need to define those values in TextField, like this:
const SearchLink = (props) => (
<MuiThemeProvider muiTheme={muiTheme}>
<TextField
onChange = {props.onChange}
value = {props.value}
floatingLabelText = "Search a Link"
name = "searchLink"
fullWidth = {true}/>
</MuiThemeProvider>
);
Related
I'm currently making a simple web frontend with react using react-autosuggest to search a specified user from a list. I want to try and use the Autosuggest to give suggestion when the user's type in the query in the search field; the suggestion will be based on username of github profiles taken from github user API.
What I want to do is to separate the AutoSuggest.jsx and then import it into Main.jsx then render the Main.jsx in App.js, however it keeps giving me 'TypeError: _ref2 is undefined' and always refer to my onChange function of AutoSuggest.jsx as the problem.
Below is my App.js code:
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Header from './views/header/Header';
import Main from './views/main/Main';
import Footer from './views/footer/Footer';
const App = () => {
return (
<>
<Header/>
<Main/> <- the autosuggest is imported in here
<Footer/>
</>
);
}
export default App;
Below is my Main.jsx code:
import React, { useState } from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import axios from 'axios';
import { useEffect } from 'react';
import AutoSuggest from '../../components/AutoSuggest';
const Main = () => {
const [userList, setUserList] = useState([]);
useEffect(() => {
axios.get('https://api.github.com/users?per_page=100')
.then((res) => setUserList(res.data))
.catch((err) => console.log(err));
}, [])
return (
<Container>
<br/>
<Row>
<AutoSuggest userList={userList} placeHolderText={'wow'} />
</Row>
</Container>
);
}
export default Main;
Below is my AutoSuggest.jsx code:
import React, { useState } from "react";
import Autosuggest from 'react-autosuggest';
function escapeRegexCharacters(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function getSuggestions(value, userList) {
const escapedValue = escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return userList.filter(user => regex.test(user.login));
}
function getSuggestionValue(suggestion) {
return suggestion.name;
}
function renderSuggestion(suggestion) {
return (
<span>{suggestion.name}</span>
);
}
const AutoSuggest = ({userList, placeHolderText}) => {
const [value, setValue] = useState('');
const [suggestions, setSuggestions] = useState([]);
const onChange = (event, { newValue, method }) => { <- error from console always refer here, I'm not quite sure how to handle it..
setValue(newValue);
};
const onSuggestionsFetchRequested = ({ value }) => {
setValue(getSuggestions(value, userList))
};
const onSuggestionsClearRequested = () => {
setSuggestions([]);
};
const inputProps = {
placeholder: placeHolderText,
value,
onChange: () => onChange()
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={() => onSuggestionsFetchRequested()}
onSuggestionsClearRequested={() => onSuggestionsClearRequested()}
getSuggestionValue={() => getSuggestionValue()}
renderSuggestion={() => renderSuggestion()}
inputProps={inputProps} />
);
}
export default AutoSuggest;
The error on browser (Firefox) console:
I have no idea what does the error mean or how it happened and therefore unable to do any workaround.. I also want to ask if what I do here is already considered a good practice or not and maybe some inputs on what I can improve as well to make my code cleaner and web faster. Any input is highly appreciated, thank you in advance!
you have to write it like this... do not use the arrow function in inputProps
onChange: onChange
I am using Draft.js to create Rich Text Editor.
This is Parent:
import React from 'react'
import RichTextEditor from './RichTextEditor'
import {useEffect, useState, useCallback} from "react"
import { EditorState, convertToRaw } from 'draft-js';
function AddPage() {
// MY STATE
const [editorState, setEditorState] = useState({editorState: EditorState.createEmpty()});
// MY CALLBACKS ATTEMPTS
function onChangeCallback(editorState) {
const contentState = editorState.getCurrentContent();
console.log(convertToRaw(contentState))
setEditorState({editorState});
}
// const onChangeCallback = useCallback((editorState) => {
// const contentState = editorState.getCurrentContent();
// console.log(convertToRaw(contentState))
// setEditorState({editorState});
// }, []);
// const onChangeCallback = ({editorState}) => {
// setEditorState({editorState});
// }
return (
<div>
<div className="app__body">
{editorState && <RichTextEditor editorState={editorState} onChangeCallback={onChangeCallback} /> }
</div>
</div>
)
}
export default AddPage
And this is Child (I made it as short as I could)
import React from 'react'
import { Editor, RichUtils, getDefaultKeyBinding } from 'draft-js';
import './RichTextEditor.css'
import 'draft-js/dist/Draft.css';
class RichTextEditor extends React.Component {
constructor(props) {
super(props);
this.state = this.props.editorState; // <----- PASSED STATE
this.onChange = this.props.onChangeCallback; //<----- PASSED CALLBACK
this.focus = () => this.refs.editor.focus();
this.handleKeyCommand = this._handleKeyCommand.bind(this);
this.mapKeyToEditorCommand = this._mapKeyToEditorCommand.bind(this);
this.toggleBlockType = this._toggleBlockType.bind(this);
this.toggleInlineStyle = this._toggleInlineStyle.bind(this);
}
_handleKeyCommand(command, editorState) {
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
this.onChange(newState);
return true;
}
return false;
}
_mapKeyToEditorCommand(e) {
if (e.keyCode === 9 /* TAB */) {
const newEditorState = RichUtils.onTab(
e,
this.state.editorState,
4, /* maxDepth */
);
if (newEditorState !== this.state.editorState) {
this.onChange(newEditorState);
}
return;
}
return getDefaultKeyBinding(e);
}
_toggleBlockType(blockType) {
this.onChange(
RichUtils.toggleBlockType(
this.state.editorState,
blockType
)
);
}
_toggleInlineStyle(inlineStyle) {
this.onChange(
RichUtils.toggleInlineStyle(
this.state.editorState,
inlineStyle
)
);
}
render() {
let className = 'RichEditor-editor';
var contentState = this.state.editorState.getCurrentContent();
if (!contentState.hasText()) {
if (contentState.getBlockMap().first().getType() !== 'unstyled') {
className += ' RichEditor-hidePlaceholder';
}
}
return (
<div className="RichEditor-root">
<button onClick={this.onChange}>aaa</button>
<div className={className} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
handleKeyCommand={this.handleKeyCommand}
keyBindingFn={this.mapKeyToEditorCommand}
onChange={this.onChange}
placeholder="Add your text here"
ref="editor"
spellCheck={true}
/>
</div>
</div>
);
}
}
export default RichTextEditor
My problem is that when I click a key, editorState in Parent callback contains the letter, but when I click again, it looks like editorState is a new object with one, the last clicked letter. I never see anything in the editor.
editorState is the object that should contain a lot of blocks, each corresponding to another line of text. Instead, this is console output:
BTW. I need to store editorState in Parent. When I move more or less the same useState code to the child, it behaves the way it should.
It seems that it was a beginner question hidden in Draft.js. I did not understand basic hooks' functionality. Each time I run callback, setEditorState re-renders the component. To re-render it with a memoized version of the callback, and it’ll only be changed if one of the dependencies has changed in callback (see last line):
const onChangeCallback = useCallback((editorState) => {
const contentState = editorState.getCurrentContent();
console.log(convertToRaw(contentState))
setEditorState({editorState});
}, [editorState]);
This helped me
How to prevent re-rendering of components that have not changed?
I'm trying to test that a component updates as it should due to changes in an input element. I use the fireEvent.change()-function, and if I then check the value of the node I found using getByPlaceholderText it has updated as it should. However I cannot see the changes in the react component itself.
This might be because the changes don't happen until a rerender; how would I test this? react-testing-library's rerender appears to start the component "from scratch" (i.e. without the new input value), and waitForElement never finds what it's waiting for.
Here's the component TestForm.js:
import React from 'react';
import { withState } from 'recompose';
const initialInputValue = 'initialInputValue';
const TestForm = ({ inputValue, setInputValue }) => (
<>
{console.log('inputValue', inputValue)}
<input value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="placeholder" />
{inputValue !== initialInputValue && <div>Input has changed</div>}
</>
);
export default withState('inputValue', 'setInputValue', initialInputValue)(TestForm);
And here's the test, run using npx jest test.js:
import React from 'react';
import { cleanup, fireEvent, render, waitForElement } from 'react-testing-library';
import TestForm from './TestForm';
afterEach(cleanup);
describe('TestForm', () => {
it('Change input', async () => {
const { getByPlaceholderText, getByText } = render(<TestForm />);
const inputNode = getByPlaceholderText('placeholder');
fireEvent.change(inputNode, { target: { value: 'new value' } });
console.log('inputNode.value', inputNode.value);
await waitForElement(() => getByText('Input has changed'));
});
});
This code works for me:
import React from "react";
const initialInputValue = "initialInputValue";
class TestForm extends React.Component {
constructor(props) {
super(props);
this.state = { inputValue: initialInputValue };
}
render() {
const { inputValue } = this.state;
return (
<div>
{console.log("inputValue", inputValue)}
<input
value={inputValue}
onChange={e => this.setState({ inputValue: e.target.value })}
placeholder="placeholder"
/>
{inputValue !== initialInputValue && <div>Input has changed</div>}
</div>
);
}
}
import { render, cleanup, fireEvent } from "react-testing-library";
import "jest-dom/extend-expect";
afterEach(cleanup);
test("form", () => {
const { getByPlaceholderText, getByText } = render(<TestForm />);
fireEvent.change(getByPlaceholderText("placeholder"), {
target: { value: "new value" }
});
expect(getByText("Input has changed")).toBeInTheDocument();
});
It does not work in codesandbox though, I guess they have some issues with keeping the browser and the test environment separated.
using user-event library
import { render, screen } from '#testing-library/react';
import userEvent from '#testing-library/user-event';
afterEach(cleanup);
test("form", async () => {
const user = userEvent.setup();
const { getByPlaceholderText, getByText } = render(<TestForm />);
await user.type(getByPlaceholderText("placeholder"), "new value");
await waitFor(() => {
expect(getByText("Input has changed")).toBeInTheDocument();
});
});
I have created a search box inside component. So I am calling onchange function outside in parent App.js. Now I am trying to dispatch that function if I type anything in search box but I can't access that function outside my class.
How to dispatch my function?
Please find my source code below:
import React, {Component} from "react";
import {connect} from "react-redux";
import { User } from "../components/User";
import { Main } from "../components/Main";
import Data from "../components/Data";
import MovieListing from '../components/MovieListing';
import Header from '../components/Header'
import { setName, getApiData } from "../actions/userActions";
import {apiFetch} from "../actions/dataActions"
import {searchFetch} from "../actions/searchActions"
class App extends Component {
constructor(props){
super(props)
this.searchQuery = this.searchQuery.bind(this);
}
searchQuery( query ) {
}
render() {
let dataSet=this.props.data.data.results;
let imagePath = []
let original_title = []
let release_date = []
let original_language = []
if(dataSet){
dataSet.forEach(function (value, key) {
imagePath.push(<Data key={key} imagePath={value.backdrop_path} release_date={value.release_date} original_title={value.original_title} original_language={value.original_language} />)
original_title.push(value.original_title)
})
return(
<div className="wrapper">
<Header searchQuery = { this.searchQuery } />
<div className="movies-listing">
<div className="container">
<MovieListing imagePath={imagePath} release_date={release_date} original_title={original_title} original_language={original_language} />
</div>
</div>
</div>
)
}else{
return(
<div className="middle-loader">
<h1>Loading</h1>
</div>
)
}
// console.log("this.props",this.props);
}
}
const mapStateToProps = (state) => {
return {
user: state.user,
math: state.math,
data: state.data,
searchData: state.searchData
};
};
const mapDispatchToProps = (dispatch) => {
return dispatch(apiFetch()), {searchQuery: (query) => {searchFetch(query)}}
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
Here I can't access that {searchQuery: (query) => {searchFetch(query)}} because of not accessible that function outside class.
HELP WOULD BE APPRECIATED!!
mapDispatchToProps takes/passes the dispatch function and then return searchQuery function as a prop.
const mapDispatchToProps = (dispatch) => {
return {
searchQuery: (query) => { dispatch(searchFetch(query)) }
}
};
Then in the Header component pass the searchQuery prop
<Header searchQuery={ this.props.searchQuery } />
I have just taken over a new reactjs project -- and I am trying to review how language switching has been invoked.
so like there are two links in the footer to do this language switch.
//footer.js
import React from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { selectLanguage, getLangDetails } from '../../actions/action_language'
import langObject from './Footer.lang'
class Footer extends React.Component {
constructor (props) {
super(props)
this.changeLanguageToGerman = this.changeLanguageToGerman.bind(this)
this.changeLanguageToEnglish = this.changeLanguageToEnglish.bind(this)
}
changeLanguageToGerman () {
this.props.selectLanguage('de')
}
changeLanguageToEnglish () {
this.props.selectLanguage('en')
}
render () {
let activeLang = 'language--active'
let alternativeLang = 'language--hover'
const lang = getLangDetails(this.props.active_language, langObject)
return (
<div>
<footer className='main-footer show-for-medium-only'>
<div className='medium-15 columns'>
<p className='text--white grid__row--offset--15 footer-text'>
<Link to={this.props.deURL} className={`text--white footer-text ${this.props.active_language === 'de' ? activeLang : alternativeLang}`} onClick={this.changeLanguageToGerman}>DE</Link>
|
<Link to={this.props.enURL} className={`text--white footer-text ${this.props.active_language === 'en' ? activeLang : alternativeLang}`} onClick={this.changeLanguageToEnglish}>EN</Link>
</p>
</div>
</footer>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
active_language: state.active_language
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators({selectLanguage: selectLanguage}, dispatch)
}
const { string, func } = React.PropTypes
Footer.propTypes = {
deURL: string,
enURL: string,
selectLanguage: func,
active_language: string
}
export default connect(mapStateToProps, mapDispatchToProps)(Footer)
// header.js
import React from 'react'
import { connect } from 'react-redux'
import { getLangDetails } from '../../actions/action_language'
import langObject from './Header.lang'
class Header extends React.Component {
render () {
let transparent
transparent = this.props.transparent ? 'transparent' : ''
const lang = getLangDetails(this.props.active_language, langObject)
return (
<div>
<header className={` main_headerbar__landing transition show-for-large-up ${transparent} `}>
<div className='contain-to-grid'>
{lang}
</div>
</header>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
active_language: state.active_language
}
}
const { bool, string } = React.PropTypes
Header.propTypes = {
transparent: bool,
active_language: string
}
export default connect(mapStateToProps)(Header)
--- so these are the header/footer components - and each has a json file that splits into an array of lang.
there is a file that looks like some global js that I think hooks into this - but I am struggling to extend this functionality into the rest of the site components/pages
//action_language.js
export const LANGUAGE_SELECTED = 'LANGUAGE_SELECTED'
export function selectLanguage (language) {
return {
type: LANGUAGE_SELECTED,
payload: language
}
}
export function getLangDetails (language = 'de', langObject) {
const langData = langObject.langs.filter((langVar) => langVar.lang === language)
return langData['0'].lines
}
ok - so here is the first page -- called services. Now what throws me first here is rather than use active_language its now just language.
//services.js
import React from 'react'
import Header from '../HeaderLanding/Header'
import Footer from '../Footer/Footer'
import NoBundle from './NoBundle'
import HowTiles from './HowTiles'
import CarouselTiles from './CarouselTiles'
import YourAdvantages from './YourAdvantages'
import InformationTiles from './InformationTiles'
import ContactTiles from './ContactTiles'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { selectLanguage, getLangDetails } from '../../actions/action_language'
// language file
import langObject from './services.lang.json'
// services css
import './services.css'
// getting the distinct URLs from the lang files
const deURL = langObject.langs[0].pageURL
const enURL = langObject.langs[1].pageURL
const Spacers = () => (
<div>
<div className='row show-for-large-up' style={{ height: '250px' }} />
<div className='row show-for-medium-only' style={{ height: '150px' }} />
<div className='row show-for-small-only' style={{ height: '80px' }} />
</div>
)
class Services extends React.Component {
constructor (props) {
super(props)
this.language = props.match.params.langURL
}
componentWillMount () {
document.getElementById('body').className = 'overlay-background-services'
this.updateLanguage()
}
updateLanguage () {
console.log('updatelang', this.language)
if (this.language === 'de' || !this.language) {
this.props.selectLanguage('de')
} else {
this.props.selectLanguage('en')
}
}
componentWillUnmount () {
document.getElementById('body').className = ''
}
render () {
const lang = getLangDetails(this.language, langObject)
return (
<div>
<Header transparent />
<Spacers />
<NoBundle lang={lang} />
<HowTiles />
<CarouselTiles />
<YourAdvantages />
<InformationTiles />
<ContactTiles />
<Footer deURL={deURL} enURL={enURL} />
</div>
)
}
}
const mapStateToProps = (state) => {
return {
language: state.language
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators({selectLanguage: selectLanguage}, dispatch)
}
const { func, string, object } = React.PropTypes
Services.propTypes = {
selectLanguage: func,
langURL: string,
params: object,
match: object
}
export default connect(mapStateToProps, mapDispatchToProps)(Services)
The Footer component deals with setting the current language by invoking the Redux action creator selectLanguage. Essentially this dispatches an action (you can think of this as a custom event with some corresponding data - the language) to the store that will persist the user's language selection for use elsewhere.
In order to consume the language in other components, that language selection needs to be passed into the component (in this case the Header) from the Redux store.
This is the code of interest in header that does that...
const mapStateToProps = (state) => {
return {
active_language: state.active_language
}
}
export default connect(mapStateToProps)(Header)
Here you are connecting the Header to the store, with a function that describes how the store should map values into props on your react component. state.active_language is where the language that the user has selected is stored, and this is telling it to be passed as a prop called active_language on your Header component
The connect function is a decorator that will create what's know as a Higher Order Component (HOC) which is essentially a component with props or functionality automatically injected into it (decorated in this case with an automatically passed value for the active_language prop from the store)
You can do the same for any other component that need this language setting, or go a step or two further
Instead of passing the active language name, pass the corresponding language itself...
import { getLangDetails } from '../../actions/action_language'
import langObject from './Header.lang'
const mapStateToProps = (state) => {
return {
active_language: getLangDetails(state.active_language, langObject)
}
}
export default connect(mapStateToProps)(Header)
OR better yet write another HOC that wraps any component you pass with this info...
import { getLangDetails } from '../../actions/action_language'
export default const injectLanguage = (component, langObject) => connect((state) => ({
language: getLangDetails(state.active_language, langObject)
})
)(component)
Then in subsequent components with a language prop, decorate with this
import injectLanguage from './some/where'
import langObject from './MyLanguageDetailsAwareComponent.lang'
class MyLanguageDetailsAwareComponent extends React.Component {
render() {
return this.props.language
}
}
export default injectLanguage(MyLanguageDetailsAwareComponent, langObject)