I'm trying to get this form working for the first time and would just like to know that my onclick is at least working. I'd like to inject a spy to replace the handler that my dispatchToProps is referencing as well.
So in other words I'd like to replace this:
AsyncActions.login
with loginSpy
I can't just do button.props().login = loginSpy because props are immutable at that point. I get TypeError: Can't add property login, object is not extensible
So is there a way to use restructuring through an ES6 class, specifically an ES6 react component via its constructor or something like that?
I know you can do {prop1, prop2} as a parameter in a stateless function, for example:
function FieldGroup({ id, label, help, ...props }) {
but what about ES6 classes in React?
Test
it.only('can log in successfully', async () => {
const container = shallow(<LoginContainer store={store} />),
loginContainer = shallow(<LoginContainer store={store} />),
login = loginContainer.dive().find(Login),
loginForm = login.dive().find(LoginForm),
loginFormLogin = await loginForm.props().login(),
button = loginForm.dive().find('.ft-login-button'),
loginSpy = spy()
button.props().login = loginSpy
button.simulate('click')
expect(loginSpy.calledOnce).to.be.true
})
Container
import { connect } from 'react-redux'
import React, { Component } from 'react'
import * as AsyncActions from '../actions/User/UserAsyncActions'
import Login from '../components/Login/Login'
class LoginContainer extends Component {
componentWillMount(){
// const requested = this.user.requested
}
render(){
return( <Login login={this.props.login} /> )
}
}
const mapStateToProps = state => {
return {
requesting: state.user.requesting,
token: state.user.token,
session: state.user.session
}
}
export const mapDispatchToProps = {
login: AsyncActions.login
}
export { Login }
export default connect(mapStateToProps, mapDispatchToProps)(LoginContainer)
LoginForm
import React, { Component } from 'react'
import { Button, FormControl, FormGroup, ControlLabel, PageHeader } from 'react-bootstrap'
class LoginForm extends Component {
render(){
return (
<div className='ft-login-form'>
<PageHeader className='ft-header'>Login</PageHeader>
<form>
<FormGroup controlId="formBasicText" >
<ControlLabel>Email</ControlLabel>
<FormControl
bsSize="small"
className="ft-username"
componentClass="input"
placeholder="Enter mail"
style={{ width: 300}}
type="text"
/>
<ControlLabel>Password</ControlLabel>
<FormControl
bsSize="small"
className="ft-password"
componentClass="input"
placeholder="Enter Password"
style={{ width: 300}}
type="text"
/>
</FormGroup>
<Button
className='ft-login-button'
onClick={this.props.login}
type='submit'>Login</Button>
</form>
</div>)
}
}
export default LoginForm
You should shallow render LoginForm instead of LoginContainer and simply pass loginSpy as a prop to LoginForm to test the button...
it.only('can log in successfully', async () => {
const loginSpy = spy(),
loginForm = shallow(<LoginForm login={loginSpy} />),
button = loginForm.dive().find('.ft-login-button')
button.simulate('click')
expect(loginSpy.calledOnce).to.be.true
})
Related
I installed react-router-dom v6 and I want to use a class based component, in previous version of react-router-dom v5 this.props.history() worked for redirect page after doing something but this code not working for v6 .
In react-router-dom v6 there is a hook useNavigate for functional component but I need to use it in class base component , Please help me how to use navigate in class component ?
In the react-router-dom v6, the support for history has been deprecated but instead of it, navigate has been introduced. If you want to redirect user to a specific page on success of a specific event, then follow the steps given below:
Create a file named as withRouter.js, and paste the code given below in this file:
import { useNavigate } from 'react-router-dom';
export const withRouter = (Component) => {
const Wrapper = (props) => {
const navigate = useNavigate();
return (
<Component
navigate={navigate}
{...props}
/>
);
};
return Wrapper;
};
Now, in whichever class based component you want to redirect the user to a specific path/component, import the above withRouter.js file there and use this.props.navigate('/your_path_here') function for the redirection.
For your help, a sample code showing the same has been given below:
import React from 'react';
import {withRouter} from '.your_Path_To_Withrouter_Here/withRouter';
class Your_Component_Name_Here extends React.Component{
constructor(){
super()
this.yourFunctionHere=this.yourFunctionHere.bind(this);
}
yourFunctionHere()
{
this.props.navigate('/your_path_here')
}
render()
{
return(
<div>
Your Component Code Here
</div>
)
}
}
export default withRouter(Your_Component_Name_Here);
Above Code works Perfect. And this is just a small extension.
If you want onclick function here is the code:
<div className = "row">
<button className= "btn btn-primary"
onClick={this.yourFunctionHere}>RedirectTo</button>
</div>
in class base component for redirect user follow this step :
first import some component like this
import { Navigate } from "react-router-dom"
now make a state for Return a boolean value like this:
state = {
redirect:false
}
now insert Naviagate component to bottom of your component tree
but use && for conditional rendring like this :
{
this.state.redirect && <Navigate to='/some_route' replace={true}/>
}
now when you want redirect user to some page just make true redirect state
on a line of code you want
now you can see you navigate to some page :)
Try this:
import {
useLocation,
useNavigate,
useParams
} from "react-router-dom";
export const withRouter = (Component) => {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
and just used this function, in my case:
import { withRouter } from '../utils/with-router';
import './menu-item.styles.scss';
const MenuItem = ({title, imageUrl, size, linkUrl,router}) =>(
<div
className={`${size} menu-item`} onClick={() => router.navigate(`${router.location.pathname}${linkUrl}`)}
>
<div className='background-image'
style={{
backgroundImage: `url(${imageUrl})`
}} />
<div className="content">
<h1 className="title">{title.toUpperCase()}</h1>
<span className="subtitle">SHOP NOW</span>
</div>
</div>
)
export default withRouter(MenuItem);
I found this solution here https://www.reactfix.com/2022/02/fixed-how-can-i-use-withrouter-in-react.html
Other solution is useNavigate, for example:
<button onClick={() => {navigate("/dashboard");}} >
Dashboard
</button>
In a react class component use <Navigate>. From the react router docs:
A <Navigate> element changes the current location when it is rendered. It's a component wrapper around useNavigate, and accepts all the same arguments as props.
Try creating a reusable functional Component like a simple button and you can use it in your class component.
import React from "react";
import { useNavigate } from "react-router-dom";
const NavigateButton = ( { buttonTitle, route,isReplaced}) => {
const navigate = useNavigate();
return (
<button
className = "btn btn-primary"
onClick = { () => {
navigate( route , {replace:isReplaced} )
}}
>
{buttonTitle}
</button>;
);
});
export default NavigateButton;
After this, you can use NavigateButton in any of your class Components. And it will work.
<NavigateButton title = {"Route To"} route = {"/your_route/"} isReplaced = {false}/>
Found this explanation from the GitHub react-router issue thread, this explained how to use react-router 6 with class components
https://github.com/remix-run/react-router/issues/8146
I got this code from the above issue explanation
import React,{ Component} from "react";
import { useNavigate } from "react-router-dom";
export const withNavigation = (Component : Component) => {
return props => <Component {...props} navigate={useNavigate()} />;
}
//classComponent
class LoginPage extends React.Component{
submitHandler =(e) =>{
//successful login
this.props.navigate('/dashboard');
}
}
export default withNavigation(LoginPage);
If you need to use params for data fetching, writing a logic in your ClassComponent and render component depending on them, then create wrapper for your ClassComponentContainer
import { useLocation, useParams } from 'react-router-dom';
import ClassComponentContainer from './ClassComponentContainer';
export default function ClassComponentWrap(props) {
const location = useLocation();
const params = useParams();
return <ClassComponentContainer location={location} params={params} />
}
after it just use params in ClassComponent which is in props
import React from 'react';
import { connect } from 'react-redux';
import axios from 'axios';
import PresentationComponent from './PresentationComponent';
class ClassComponent extends React.Component {
componentDidMount() {
let postID = this.props.params.postID;
axios.get(`https://jsonplaceholder.typicode.com/posts/${postID}`)
.then((response) => {console.log(response)})
}
render() {
return <PresentationComponent {...this.props} />
}
}
const mapStateToProps = (state) => {...}
const mapDispatchToProps = (dispatch) => {...}
const ClassComponentContainer = connect(mapStateToProps, mapDispatchToProps)(ClassComponent);
export default ClassComponentContainer;
and use ClassComponentWrap component in Route element attribute
import { BrowserRouter, Route, Routes } from "react-router-dom";
import ClassComponentWrap from './components/ClassComponentWrap';
export default function App(props) {
return (
<BrowserRouter>
<Routes>
<Route path="/posts/:postID?" element={<ClassComponentWrap />} />
</Routes>
</BrowserRouter>
);
}
Here is my solution:
import React, { Component } from "react";
import { useNavigate } from "react-router-dom";
class OrdersView extends Component {
Test(props){
const navigate = useNavigate();
return(<div onClick={()=>{navigate('/')}}>test{props.test}</div>);
}
render() {
return (<div className="">
<this.Test test={'click me'}></this.Test>
</div>);
}
}
I am trying to make a movie search function using React, Axios, and movieDB API. The functionality I am trying to implement right now is typing in a movie into the search bar and clicking the submit button will return the movie title as an H1 element.
My onClick function does not work: <button onClick={(e)=>clickHandler()}>submit</button>
componentDidMount() will work only when the page refreshes and you cannot search for anything as the submit button is broken.
I am not sure how to implement this, but I would also not mind if I could get it to search by hitting enter instead of using a button, whichever is easier.
Here is my code so far.
App.js
import React from "react"
import Movielist from './components/Movielist'
function App() {
return (
<div>
<input type="search" id="search" />
<button onClick={(e)=>clickHandler()}>submit</button>
<h1 id="title">title</h1>
<Movielist />
</div>
)
}
export default App
Movielist.js
import React from 'react';
import axios from 'axios';
export default class Movielist extends React.Component {
state = {
title: ""
}
componentDidMount() {
const API_KEY = '***********************';
const query = document.getElementById('search').value;
axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
.then(res => {
const title = res.data['results'][0]['title'];
this.setState({ title });
})
}
render() {
return (
<h1>{this.state.title}</h1>
)
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
import React from 'react';
import axios from 'axios';
export default class Movielist extends React.Component {
state = {
title: ""
}
clickHandler = (event) => {
if (event.keyCode === 13) {
const query = event.target.value;
const API_KEY = '***********************';
axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
.then(res => {
const title = res.data['results'][0]['title'];
this.setState({ title });
})
}
}
render() {
return (
<input type="search" id="search" onKeyDown={event => this.clickHandler(event)} />
<h1>{this.state.title}</h1>
)
}
}
You should call API to get the movie list after hitting the button, then pass the data that you've got to Movielist. Try this:
In App.js:
import React from "react"
import axios from 'axios'
import Movielist from './components/Movielist'
function App() {
const [movieList, setMovieList] = React.useState([])
const handleOnSubmit = () => {
const API_KEY = '***********************';
const query = document.getElementById('search').value;
axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
.then(res => {
const title = res.data['results'][0]['title'];
setMovieList(res.data['results'])
})
}
return (
<div>
<input type="search" id="search" />
<button onClick={handleOnSubmit}>submit</button>
<h1 id="title">title</h1>
<Movielist movieList={movieList}/>
</div>
)
}
export default App
In Movielist.js:
import React from 'react';
const Movielist = ({movieList}) => {
return (
<div>
{
movieList.map(movie => <h1 key={movie.key}>{movie.title}</h1>)
}
<div/>
)
}
}
export default Movielist
import React, {useState} from "react"
import axios from 'axios';
import Movielist from './components/Movielist'
const [title, setTitle] = useState("")
const API_KEY = '***********************'
function App() {
const clickHandler = () => {
const query = document.getElementById('search').value;
axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
.then(res => {
const title = res.data['results'][0]['title'];
setTitle(title);
})
}
return (
<div>
<input type="search" id="search" />
<button onClick={clickHandler}>submit</button>
<h1 id="title">title</h1>
<Movielist title={title} />
</div>
)
}
export default App
just move call api handle to your onclik func then pass title props to movie list
If you want to query the API after user push submit button. You should put your call to API in the call handler, then pass the state from App to MovieList as props
export class App extends React.Component {
state = {
title: ""
}
clickHandler() {
const API_KEY = '***********************';
const query = document.getElementById('search').value;
axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`).then(res => {
const title = res.data['results'][0]['title'];
this.setState({ title });
});
}
render() {
return (
<div>
<input type="search" id="search" />
<button onClick={(e)=>clickHandler()}>submit</button>
<h1 id="title">title</h1>
<Movielist list={this.state.title}/>
</div>
)
}
}
export class MovieList extends React.Component {
render() {
<h1>{this.props.title}</h1>
}
}
Alternatively, you can wrap the input in a element and use onSubmit + evt.preventDefault() instead, by doing so you can handle button click and pressing "Enter" to submit.
I was given below task in an interview, here the task is about getting a response from API using ajax call on button click and display it on a page.
I have a top component inside App.js, with two child components as MyButton.js and MyPage.js and the service code in MyAPI.js
Below are the file contents:
App.js
import React, { Component } from 'react';
import MyAPI from './services/MyAPI';
import MyButton from './components/MyButton';
import MyPage from './components/MyPage';
class App extends Component {
constructor() {
super();
this.state= {
'apiResponse': ''
};
}
handleButtonClick = () => {
MyAPI.getAPIResponse().then((res) => {
res => this.setState({ apiResponse })
});
}
render() {
return (
<div>
<center><MyButton onClickButton={this.handleButtonClick}></MyButton></center>
<MyPage apiResponse={this.props.apiResponse}></MyPage>
</div>
);
}
}
export default App;
MyButton.js
import React from 'react';
import PropTypes from 'prop-types';
import Button from '#material-ui/core/Button';
const MyButton = (() => (
<div className="button-container">
<MyButton variant="extendedFab" color="primary"
onClick={this.props.onClickButton}>
Call API
</MyButton>
</div>
));
MyButton.propTypes = {
onClickButton: PropTypes.func
}
export default MyButton;
MyPage.js
import React from 'react';
import PropTypes from 'prop-types';
import List from '#material-ui/core/List';
import ListItem from '#material-ui/core/ListItem';
import ListItemText from '#material-ui/core/ListItemText';
import Paper from '#material-ui/core/Paper';
const MyPage = (() => (
<Paper className="container">
<List>
<ListItem>
<ListItemText>Name: {this.props.apiResponse.split(" ")[0]}</ListItemText>
</ListItem>
</List>
</Paper>
));
MyPage.propTypes = {
apiResponse: PropTypes.string
}
export default MyPage;
MyAPI.js
import axios from 'axios';
export default {
getAPIResponse() {
return axios.get("--url to get user name and age as json--").then(response => {
return response.data;
});
}
};
Here the JSON data contains the name of a sample user just for demo purpose eg: John Doe. I need to display only John on my page as per the given task.
When I run this application I am getting errors at my MyButton.js and MyPage.js in logs.
In MyButton.js the error is at line onClick={this.props.onClickButton}, it says cannot access props on undefined. If I change it to onClick={this.onClickButton}, I got an error as, cannot access onClickButton on undefined. What is the correct way to do this here, please help.
Also same applies to MyPage.js at line {this.props.apiResponse.split(" ")[0], also is it the right way to use the split method here to get the first name from John Doe?
Your MyButtn and MyPage both are functional components. To access the props you do not need to use this. props are taken as params in case of functional components.
MyButton
const MyButton = ((props) => (
<div className="button-container">
<MyButton variant="extendedFab" color="primary"
onClick={props.onClickButton}>
Call API
</MyButton>
</div>
));
MyPage
const MyPage = ((props) => (
<Paper className="container">
<List>
<ListItem>
<ListItemText>Name: {props.apiResponse.split(" ")[0]}</ListItemText>
</ListItem>
</List>
</Paper>
));
once the response success you have to store in the variable
var a = "jhon doe";
var data = a.split(" ");
data[0];
you can do this in a parent component.
I'm working on simple form element using react-js.
There are three component:
App
TakeInput
Index
problem is when user put text in input field setState() function not work properly and data not updated. For testing purpose when i'm placing console.log in app js component it shows undefined on console. anyone sort this please. I want to console the updated data when state update
App.js
import React, { Component } from 'react';
import InputField from './TakeInput';
class App extends Component {
state = {
userInp : '',
outText : ''
}
handlechanger2 = (v) => {
this.setState( () => ({
userInp: v,
}))
console.log(this.userInp);
}
render() {
return (
<div className="App">
<InputField changingVal={this.handlechanger2}/>
</div>
);
}
}
export default App;
TakeInput.JS
import React, { Component } from 'react';
class TakeInput extends Component{
state={
txt: ''
}
handlerChange = (e)=>{
const { changingVal } = this.props;
const v = document.getElementById("userInput").value;
changingVal(v);
// console.log(e.target.value);
this.setState({ txt: e.target.value })
}
render(){
return(
<input type="text" name="userInput" id="userInput" placeholder="Please Enter Text" onChange={this.handlerChange} value={this.txt}/>
)
}
}
export default TakeInput;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
it is about you are developing wrong way. I think you text input should be at your parent component
To read from state you should use this.state.abc
import React, { Component } from 'react';
class TakeInput extends Component{
handlerChange = (e)=>{
this.props.onChange(e.target.value);
}
render(){
return(
<input type="text" name="userInput" placeholder="Please Enter Text" onChange={this.handlerChange} value={this.props.txt}/>
)
}
}
export default TakeInput;
import React, { Component } from 'react';
import InputField from './TakeInput';
class App extends Component {
state = {
userInp : '',
outText : ''
}
handlechanger2 = (v) => {
this.setState( () => ({
userInp: v,
}))
console.log(this.state.userInp);
}
render() {
return (
<div className="App">
<InputField txt={this.state.userInp} onChange={this.handlechanger2}/>
</div>
);
}
}
export default App;
You're trying to console.log this.userInp. It should be this.state.userInp.
Also to see the update right after the last set state, you can do the following:
handlechanger2 = (v) => {
this.setState( () => ({
userInp: v,
}), function(){ console.log(this.state.userInp);}) // set a callback on the setState
}
I'm having an issue where when I want to dispatch an action, fetchRewardByPromoCodeAction it's saying that the action I want to dispatch is not a function.
In the the form, I use the the event handleer onSubmit then use handleSubmit. I noticed that my props becomes undefined so, which leads me to thinking that the connect function isn't working as expected. Any assistance would be helpful. Here's the code.
import React, { Component } from 'react';
import { connect
} from 'react-redux';
import PromoCodeInput from 'components/promoCodeForm/PromoCodeInput';
import { fetchRewardByPromoCode, resetValidations } from 'rewards/ducks';
import Button from 'button/Button';
export class AdminRewardPage extends Component<Props> {
constructor(props) {
super(props);
this.state = {
promoCodeText: '',
};
}
onPromoCodeChange = (event) => {
this.setState({
promoCodeText: event.target.value,
});
const { resetValidationsAction } = this.props;
resetValidationsAction();
};
handleSubmit = (event) => {
event.preventDefault()
const { fetchRewardByPromoCodeAction } = this.props;
const { promoCodeText } = this.state;
fetchRewardByPromoCodeAction(promoCodeText);
}
render() {
const { promoCodeText } = this.state
return (
<div>
<h1>AdminRewardPage</h1>
<form onSubmit={this.handleSubmit}>
<PromoCodeInput inputValue={promoCodeText} onChangeHandler={this.onPromoCodeChange} />
<Button type="submit" label="Find By PromoCode" fullWidth />
</form>
</div>
)
}
}
const mapDispatchToProps = (dispatch) => ({
resetValidationsAction: () => dispatch(resetValidations()),
fetchRewardByPromoCodeAction: (promoCodeText) => dispatch(fetchRewardByPromoCode(promoCodeText)),
});
export default connect(null, mapDispatchToProps)(AdminRewardPage);
in rewards/ducks.js
export const fetchRewardByPromoCode = (promoCode: string): FSAModel => ({
type: FETCH_REWARD_BY_PROMOCODE,
payload: promoCode,
})
---EDIT--WITH--ANSWER---
#Bartek Fryzowicz below helped lead me to right direction. I forgot to look in my index.js file where my routes are
Previously I had
import { AdminRewardPage } from 'scenes/AdminRewardPage'
instead of
import AdminRewardPage from 'scenes/AdminRewardPage'
<Router history={ history }>
<Switch>
<Route exact path={ `/rewards` } component={AdminRewardPage} />
</Switch>
</Router>
I didn't bother to look how I was importing it.
LESSON
Look at where and HOW your files are being imported and exported.
You're trying to call fetchRewardByPromoCode function inside mapDispatchToProps but such function (fetchRewardByPromoCode) is not declared inside mapDispatchToProps scope nor in parent scope. Maybe you have forgotten to import it?
Answer update:
Please make sure that when you use the component you use default export (not named export) since named export is the presentational component not connected to redux store. You have to use container component connected to redux so make sure you import it like this:
import AdminRewardPage from '/somePath'
not
import { AdminRewardPage } from '/somePath'