ReduxForm data initial on Load of Form - javascript

Using redux I created a form and I am able to dispatch actions, validations and is working fine without any issues. But load data/initialize on to form field(ReduxForm) not populating data but code executed, can anyone help me in fixing the issues or where I am going wrong, code executed fine but the data not populating on the respective form fields
import "../../views/CSS/Organization.css";
import { Container, Row, Col } from "react-bootstrap";
import {createOrganization} from "../../store/actions/org_actions"
import {connect} from "react-redux"
import moment from 'moment'
import {Field, reduxForm} from 'redux-form'
class Organization extends Component {
componentDidMount(){
}
renderInputField = (field)=>(
<div class='form-group' >
<div class='oddT-icon-input' >
<input {...field.input} placeholder={`${field.placeHolder}`} class='oddT-text' />
<i class={`${field.icon}`}></i>
</div>
<div class="validation-error">{field.meta.touched?field.meta.error:""}</div>
</div>
)
render() {
return (
<div>
<Row>
<div class='col-sm-6' >
<label htmlFor="fePassword">Organization Name</label>
<Field
name="orgName"
component={this.renderInputField}
placeHolder="Organization Name"
icon="fa fa-user"
/>
</div>
</Row>
);
}
}
function mapStateToProps(state,props){
console.log(state)
return {
success: {orgName:"ARSCCOM"},
initialValues :{orgName:"ARSCCOM"}
}
}
export default reduxForm({
validate,
form: 'Organization',
enableReinitialize : true
})(connect(mapStateToProps,{createOrganization})(Organization))
Thank you so much

Related

how to connect a handleSubmit to another page with condition in react?

when the user fills the sing up form and clicks the sing up button it has to be two scenarios
first: if the password and confirm password is matching it has to route to the dashboard page
second: if the password and confirm password is not matching it has to alert a massage ("Passwords do not match")
mine I used condition at Log.jsx down below for a function called handlesubmit , in that condition the first part of the condition is not working but the second part of the condition that regarding the second scenario is working and alerting the massage
here is my code and some screenshots
Log.jsx
import React from "react";
import "./log.css";
import { useState } from "react";
import { Link } from "react-router-dom";
export default function Log() {
const [formData, setFormData] = useState({
fullName: "",
email: "",
password: "",
passwordConfirm: "",
});
function handleChange(event) {
const { name, value } = event.target;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value,
}));
}
function handleSubmit(event) {
event.preventDefault();
if (formData.password === formData.passwordConfirm) {
return (
<Link className="link" to={"/Dashboard"}>
</Link>
);
} else {
alert("Passwords do not match");
return;
}
}
return (
<div className="loginn">
<div className="login-items">
<div className="title-log">
<p className="login-title">sing up</p>
</div>
<form className="form" onSubmit={handleSubmit}>
<span className="fullname">Fullname</span>
<input
className="input-lg"
type="name"
placeholder="Email address"
name="fullName"
onChange={handleChange}
value={formData.fullName}
></input>
<span className="email">Email</span>
<input
className="input-lg"
type="email"
name="email"
onChange={handleChange}
value={formData.email}
></input>
<span className="password">Password</span>
<input
className="input-lg"
type="password"
name="password"
onChange={handleChange}
value={formData.password}
></input>
<span className="password">Confirm Password</span>
<input
className="input-lg"
type="password"
name="passwordConfirm"
onChange={handleChange}
value={formData.passwordConfirm}
></input>
<button className="login-btn">Sing up</button>
</form>
</div>
</div>
);
}
Home.jsx
import React from 'react'
import Naav from '../../components/naav/Naav'
import Log from '../../components/log/Log'
import Footer from '../../components/footer/Footer'
export default function Home() {
return (
<div className='home'>
<Naav/>
<Log/>
<Footer/>
</div>
)
}
Dashboard.jsx
import React from "react";
import "./dashboard.css"
import Sidebar from "../../components/sidebar/Sidebar";
import Navtwo from "../../components/navtwo/Navtwo";
import Cards from "../../components/cards/Cards";
import Data from "../../components/data/Data";
import Title from "../../components/title/Title";
export default function Dashboard() {
return( <div className="dashboard">
<Sidebar/>
<Navtwo/>
<Title/>
<Cards/>
<Data/>
</div>
)
}
app.js
import React from "react";
import "./app.css";
import Headerr from "./components/headerr/Headerr";
import Naav from "./components/naav/Naav";
import Footer from "./components/footer/Footer";
import Log from "./components/log/Log";
import Sidebar from "./components/sidebar/Sidebar";
import Navtwo from "./components/navtwo/Navtwo";
import Cards from "./components/cards/Cards";
import Title from "./components/title/Title";
import Data from "./components/data/Data";
import Dashboard from "./pages/dashboard/Dashboard";
import Home from "./pages/home/Home";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
export default function App() {
const currentUser = false;
return (
<Router>
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/Dashboard" element={<Dashboard />} />
</Routes>
</Router> );
}
In your handleSubmit function, you return the Link component.
That does nothing!
There are 2 ways you can go about here.
Create a state passwordMatch, and set it inside handleSubmit. If the passwords do not match, return the Redirect element instead of the form.
Import the history and call it to navigate where you want inside the handleSubmit

reactjs preventDefault() is not preventing the page reload on form submit

EDIT: Events are not working at all, the onSubmit and onChange functions are not being called. I have another reactapp with similar form and onChange and onSubmit works OK there.
I have a form I dont want the page to refresh when I click on submit. I tried using preventDefault() but I didnt work. Even onChange is printing anything on console. This form is not on page, I am using React Router to point to='/new' and component={NewPost} (NewPost is in ./components/posts/form)
./components/posts/form.js:
import React, { Component } from "react";
import { connect } from "react-redux";
class NewPost extends Component {
state = {
title: "",
body: "",
status: 0,
};
onSubmit = (e) => {
e.preventDefault();
const post = e;
console.log(post);
};
onChange = (e) => {
console.log(e.target.value);
this.setState({
[e.target.name]: e.target.value,
});
};
render() {
const { title, body, status } = this.state;
return (
<div className="card card-body mt-4 mb-4">
<h2>New Post</h2>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Title</label>
<input
type="text"
name="title"
value={title}
onChange={this.onChange}
className="form-control"
/>
</div>
<div className="form-group">
<label>Content</label>
<textarea
type="text"
name="body"
rows="15"
value={body}
onChange={this.onChange}
className="form-control"
/>
</div>
<div className="form-group">
<button className="btn btn-primary" type="submit">
Submit
</button>
</div>
</form>
</div>
);
}
}
export default NewPost;
App.js:
import React from "react";
import NavBar from "./components/layout/navbar";
import store from "./store";
import { Provider } from "react-redux";
import Dashboard from "./components/posts/dashboard";
import NewPost from "./components/posts/form";
import {
HashRouter as Router,
Route,
Switch,
Redirect,
} from "react-router-dom";
class App extends React.Component {
render() {
return (
<Provider store={store}>
<Router>
<React.Fragment>
<div className="container">
<NavBar />
<Switch>
<Route exact path="/" component={Dashboard}></Route>
<Route exact path="/new" component={NewPost}></Route>
</Switch>
</div>
</React.Fragment>
</Router>
</Provider>
);
}
}
export default App;
Issue is not related to code. I created new react application and moved all my code now everything is working fine.

How to load a new component when button clicked?

I want to open another component which is in my example <HomePage /> when user fills a login form and clicks the submit button. I searched out and i got too many ways but not sure why none worked with me. Is there just a simple way to achieve this with React Hooks?
Login Component
const submit_login = () =>{
//code to open <HomePage /> Component
}
<form>
<div>
<input type="text" placeholder="username"/>
</div>
<div>
<input type="password" class="form-control" placeholder="password"/>
</div>
<div>
<input type="submit" onClick={submit_login} value="Login"/>
</div>
</form>
This is a very simple scenario, I believe this should be very easy to implement.
I tried router switch, hashrouter, useHistory , hookrouter but all these didn't worked. some of the solutions i found was not updated since i am using latest version of ReactJS.
Here is the example. please check
ParentComponent
import React, {useEffect, useState} from 'react';
import ChildComponent from "./ChildComponent";
function ParentComponent(props) {
const [isVisible, setIsVisible] = useState(false);
function showComponent(event) {
setIsVisible(!isVisible);
}
return (
<div>
<button onClick={showComponent} >{isVisible? 'Hide':'Show'} Component</button>
{
isVisible? <ChildComponent/>:null
}
</div>
);
}
export default ParentComponent;
ChildComponent
import React, {useEffect, useState} from 'react';
function ChildComponent(props) {
return (
<div>
This is child component
</div>
);
}
export default ChildComponent;

React 6 navigation and clicks not working as expected

Sorry to ask so many questions, but this only my second and 1/2 week working with React.
When I click on the following links, I can see the URL/URI change in the browser, but it does not seem to load the component(s). What am I missing?
import React from "react";
import { Link } from "react-router-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
import NewComponent from "./new.component";
import ListComponent from "./list.component";
class NavComponent extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
}
render() {
return (
<div className="row">
<div className="col-sm-8 col-sm-offset-2">
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand">Simple CRUD</a>
</div>
<div id="navbar" className="navbar-collapse">
<ul className="nav navbar-nav">
<li>
Coin Management
</li>
<li>
Add Coin
</li>
</ul>
</div>
</div>
</nav>
<Router>
<Route path={"ListComponent"} component={ListComponent} />
</Router>
<Router>
<Route path={"NewComponent"} component={NewComponent} />
</Router>
</div>
</div>
);
}
}
export default NavComponent;
I have tried to use Link to={"/"} and Link to={"/add"}, but the error will be - Link should be used within the Router. I know that I am missing something simple.
I have also tried creating some onClick={"window.location.href=/add"} but I received the error - Expected onClick listener to be a function, instead got a value of string type
The same error message when I use onClick='{window.location.href="/add"}' - it does look like it is trying to do it.
Do I have to build a router group, like I did in Laravel? if so, then can you point me to some examples?
The following is the NewComponent that I want the app to navigate to or load in place of the ListComponent:
import React from "react";
import Axios from "axios";
import toastr from "toastr";
import $ from "jquery";
import bootstrap from "bootstrap";
import ListComponent from "./list.component";
class NewComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: null,
price: null
};
}
submitForm(event) {
event.preventDefault();
var data = $(event.target).serialize();
toastr.clear();
var isError = false;
if (this.state.name === "") {
toastr.error("Coin name must be filled!");
isError = true;
}
if (this.state.price === 0 || this.state.price === "") {
toastr.error("Coin price must be filled!");
isError = true;
}
if (!isError) {
toastr.info("Inserting new coin data...");
Axios.post(
"http://local.kronus:8001/v2018/ng6crud/api/put-coins/" +
this.state.id +
"/" +
this.state.name +
"/" +
this.state.price,
{
id: this.state.id,
name: this.state.name,
price: this.state.price
}
)
.then(function(response) {
toastr.clear();
window.location.href = "#/";
})
.catch(function(error) {
toastr.clear();
toastr.error(error);
});
}
}
onCoinNameChange(e) {
this.setState({
id: this.state.id,
name: e.target.value.trim(),
price: this.state.price
});
}
onCoinPriceChange(e) {
this.setState({
id: this.state.id,
name: this.state.name,
price: e.target.value
});
}
render() {
return (
<div>
<form className="form-horizontal" onSubmit={this.submitForm.bind(this)}>
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="coinEmail">
Name :{" "}
</label>
<div className="col-sm-10">
<input
type="text"
name="coinName"
onChange={this.onCoinNameChange.bind(this)}
id="coinName"
className="form-control"
placeholder="Coin Name"
/>
</div>
</div>
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="coinPrice">
Price :{" "}
</label>
<div className="col-sm-10">
<input
type="number"
name="coinPrice"
onChange={this.onCoinPriceChange.bind(this)}
id="coinPrice"
className="form-control"
placeholder="Coin Price"
/>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button type="submit" className="btn btn-default">
Save
</button>
</div>
</div>
</form>
</div>
);
}
}
export default NewComponent;
BTW, zero errors and a few warnings about bootstrap as being defined but never used
Once again, thanks in advance
As #tholle said in the comments, you should only have a single Router component wrapping the entirety of your app. Normally this is done at the top most component so something like
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App';
import './index.css';
ReactDOM.render(
// here is where we are wrapping our app, <App /> in <BrowserRouter />
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root'));
registerServiceWorker();
This is normally how a Create-React-App app is set up so whatever you are using YMMV. Just remember to wrap your top level component, usually <App /> in the <BrowserRouter /> or in your code <Router /> component.
Now on to your <Route /> components, curly braces are only necessary when we need to pass JS into our components attributes. In your example, <Route path={"ListComponent"} component={ListComponent} /> the path attribute needs to be a URL, in relation to the home page, that will be responsible for rendering that component. So something more like <Route path='./list' component={ ListComponent } /> is just fine. If you needed to pass a variable into path then you would use the curly braces like so ...path={ var + '/list' }....
Lastly, to get your <NewComponent /> to load you need to import { Link } from react-router-dom and instead of using those anchor tags, use <Link to='/add'>Links to the NewComponent component</Link> and just make sure your Route component that renders the NewComponent's path attribute matches.
Helpful links
React Router 4 - Quickstart
Change anchor tags to Link
Change route path to url
https://reacttraining.com/react-router/web/example/basic
Follow react router example for better understanding

Redux Form Simple Fields

I have a simple Redux Form and tried to follow the example given here https://redux-form.com/6.2.0/docs/GettingStarted.md/ here is my code
user-form.js
import React from 'react';
import {Field, reduxForm} from 'redux-form';
class UserForm extends React.Component {
/**
* User Form goes here...
*/
render() {
const { handleSubmit } = this.props;
return (
<form role="form" onSubmit={handleSubmit}>
<div className="box-body">
<div className="form-group">
<label htmlFor="name">Full Name</label>
<Field
name="name"
component="input"
type="text"
className="form-control"
placeholder="Enter full name..."/>
</div>
<div className="form-group">
<label htmlFor="email">Email address</label>
<Field
name="email"
type="email"
component="input"
className="form-control"
placeholder="Enter email"/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<Field
name="password"
type="password"
component="input"
className="form-control"
placeholder="Password"/>
</div>
</div>
<div className="box-footer">
{/* <button type="submit" className="btn btn-primary">Save</button> */}
<button type="submit" className="btn btn-primary" value="Save">Save</button>
</div>
</form>
);
}
}
UserForm = reduxForm({
form: 'user'
})(UserForm);
export default UserForm;
Above Form is rendered by a UserPage Container
user-page.js
import React from 'react';
import Page from '../../page';
import UserForm from '../components/user-form';
import UserList from '../components/user-list';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import UserAction from '../actions';
import {showLoading, hideLoading} from 'react-redux-loading-bar';
/**
* We might want to create an Abstract Form component to
* include all common form features.
*/
class UserPage extends Page {
handleUserSubmit(values) {
console.log(values);
}
/**
* Content is loaded into page
*/
content() {
return (
<div className="row">
{/* left column */}
<div className="col-md-6">
{/* general form elements */}
<div className="box box-primary">
<div className="box-header with-border">
<h3 className="box-title">New User</h3>
</div>
{/* /.box-header */}
<UserForm onSubmit={this.handleUserSubmit}/>
</div>
{/* /.box */}
</div>
{/*/.col (left) */}
{/* right column */}
<div className="col-md-6">
{/* UserList made of <User /> */}
{this.userList()}
{/* /.box */}
</div>
{/*/.col (right) */}
</div>
);
}
}
const mapStateToProps = (state) => ({ //this gets state from reducer and maps to props
users: state.userList.users,
fetched: state.userList.fetched,
error: state.userList.error
});
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators({
dispatchShowLoading: showLoading,
dispatchHideLoading: hideLoading,
dispatchUserList: UserAction.userList
}, dispatch)
});
export default connect(mapStateToProps, mapDispatchToProps)(UserPage);
My Form successfully renders and I can see all the actions being dispatched inside the Redux Dev tools window, but when I try to enter text into the fields it won't do any thing, however the actions are dispatched like I said.
Sorry if this sounds a very basic question. I am relatively new to React and Redux and for that matter to Javascript.
In order to make redux form work, its reducer needs to be included and I forgot to include one, this fixed my issue.
import { reducer as formReducer } from 'redux-form';
const allReducers = combineReducers({
form: formReducer,
});
export default allReducers;

Categories