Passing state value from component to component? - javascript

I've seen many answer on this website and in official docs and many other places. But I couldn't able to achieve results. That's why I'm posting this question.
SO, my question is I have 3 files named:
App.js, SignUp.js and Welcome.js.
My task is to get value in form from SignUp.js page and print that value to the Welcome.js component. I read about lifting state up and higher order components but couldn't able to do it.
Any help is appreciated.
Here's my code:
App.js:
import React,{Component} from "react";
import {BrowserRouter as Router, Link, Switch, Route} from "react-router-dom";
import SignUp from './SignUp';
import Welcome from './Welcome';
class App extends Component {
render(){
var homeMessage = () =>{
return(<div><SignUp /></div>);
}
return(
<Router>
<div>
<Route exact path="/src/Welcome" component={Welcome}/>
<Route exact path="/" component={homeMessage}/>
</div>
</Router>
);
}
}
export default App;
SignUp.js;
import React,{Component} from "react";
import {Link} from "react-router-dom";
export default class SignUp extends Component {
constructor(props){
super(props);
this.state = {
firstName:''
};
}
inputData = event =>
{
this.setState({
[event.target.name]:event.target.value
});
}
submitData = event =>
{
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit={this.submitData}>
<input type="text" name="firstName" onChange={this.inputData}/>
<button type="submit"> Submit</button>
</form>
<Link to="/src/Welcome">Welcome</Link>
</div>
);
}
}
Welcome.js:
import React,{Component} from "react";
import SignUp from './SignUp';
export default class Welcome extends Component {
render(){
return(
<div>
{this.state.firstName}
</div>
);
}
}
"And please give answer if possible then in react-way only not redux or any other library. Because as per Dan Abramov article "Thinking in React" so first I want to try all scope which is available in react only."

Pass the data back to the parent from SignUp component and then pass it as a prop to the Welcome component. The other way is to store the SignUp component state in the App component so that you don't need to pass it back up when you submit.
App.js
import React,{Component} from "react";
import {BrowserRouter as Router, Link, Switch, Route} from "react-router-dom";
import SignUp from './SignUp';
import Welcome from './Welcome';
class App extends Component {
state = {
firstName: ''
}
onSignIn = (value) => {
this.setState({firstName: value});
}
render(){
return(
<Router>
<div>
<Route exact path="/src/Welcome" render={(props) => <Welcome firstName={this.state.firstName} {...props}/>}/>
<Route exact path="/" render={(props) =>{
return(<div><SignUp onSignIn={this.onSignIn} {...props} /></div>);
}}/>
</div>
</Router>
);
}
}
export default App;
SignUp.js
export default class SignUp extends Component {
constructor(props){
super(props);
this.state = {
firstName:''
};
}
inputData = event =>
{
this.setState({
[event.target.name]:event.target.value
});
}
submitData = event =>
{
event.preventDefault();
this.props.onSignIn(this.state.firstName);
}
render(){
return(
<div>
<form onSubmit={this.submitData}>
<input type="text" name="firstName" onChange={this.inputData}/>
<button type="submit"> Submit</button>
</form>
<Link to="/src/Welcome">Welcome</Link>
</div>
);
}
}
Welcome.js
import React,{Component} from "react";
import SignUp from './SignUp';
export default class Welcome extends Component {
render(){
return(
<div>
{this.props.firstName}
</div>
);
}
}
Some useful links:
How to pass data from child component to its parent in ReactJS?
Passing custom props to router component in react-router v4
ReactJS - Lifting state up vs keeping a local state

Related

How to navigate to homepage upon form submit in react web using react-router-dom v6.2.1?

I have a Smart component class page PhoneDirectory.js, where I have used BrowserRouter and Route to route to the ShowSubscribers page("/") and AddSubscribers page ("/add"). My requirement is to redirect to the ShowSubscribers page("/") upon form submission on the AddSubscribers page but not understand how to implement that. I tried using this.props.history.push("/") but it isn't working. I am new to React, can anyone please help?
import React from 'react';
import AddSubscriber from './AddSubscriber';
import ShowSubscribers from './ShowSubscribers';
import {BrowserRouter , Route, Routes} from 'react-router-dom';
export default class PhoneDirectory extends React.Component{
constructor(){
super();
this.state = {[]};
}
addSubscribers = (subscribers) =>{...}
deleteSubscribers = (subscriberId) =>{...}
render() {
return (
<BrowserRouter>
<Routes>
<Route exact path='/' element={<ShowSubscribers deleteSubscribers={this.deleteSubscribers} subscribersList={this.state.subscribersList}/>}/>
<Route exact path='/add' element={<AddSubscriber addSubscribers={this.addSubscribers}/>}/>
</Routes>
</BrowserRouter>
)
}
}
Dumb component AddSubscriber page
import React from 'react';
import Header from './Header';
import './AddSubscriber.css';
import {Link} from "react-router-dom";
export default class AddSubscriber extends React.Component {
constructor() {
super();
this.state = {
id: 0,
name:'',
phone:''
}
}
onChangeHandler = (event) =>{...}
onFormSubmitted = (event) =>{
event.preventDefault();
this.props.addSubscribers(this.state);
this.setState({id:0, name:"", phone:''});
// Need logic to redirect to "/" i.e., ShowSubscribers page
}
render() {
return (<div>
<Header heading="Add Subscriber"/>
<div className="component-body-container">
<Link to="/">
<button className="custom-btn">Back</button>
</Link>
<form className="subscriber-form" onSubmit={this.onFormSubmitted.bind(this)}>
...............
<button type="submit" className="custom-btn add-btn">Add</button>
</div>
</form>
</div>
</div>)}
}
I tried this.props.history.push("/"), but it didn't worked.
react-router-dom v6 support only hooks version i suggest since you use class component to downgrade the version of react-router-dom in package.json.
"dependencies": {
...
"react-router-dom": "5.2.1",
},
Now you need to run : npm install or yarn install
Your Route component will look like that
import React from 'react';
import AddSubscriber from './AddSubscriber';
import ShowSubscribers from './ShowSubscribers';
import { Route, Switch, BrowserRouter as Router } from 'react-router-dom';
export default class PhoneDirectory extends React.Component{
constructor(){
super();
this.state = {[]};
}
addSubscribers = (subscribers) =>{...}
deleteSubscribers = (subscriberId) =>{...}
render() {
return (
<Router>
<Switch>
<Route exact path='/'>
<ShowSubscribers {...your props goes here}/>
</Route>
<Route exact path='/add'>
<AddSubscriber {...your props goes here}/>
</Route>
</Switch>
</Router>
)
}
}
Now you are able to call this.props.history.push
import React from 'react';
import Header from './Header';
import './AddSubscriber.css';
export default class AddSubscriber extends React.Component {
constructor() {
super();
this.state = {
id: 0,
name:'',
phone:''
}
}
onChangeHandler = (event) =>{...}
onFormSubmitted = (event) =>{
event.preventDefault();
this.props.addSubscribers(this.state);
this.setState({id:0, name:"", phone:''});
// Need logic to redirect to "/" i.e., ShowSubscribers page
}
render() {
return (<div>
<Header heading="Add Subscriber"/>
<div className="component-body-container">
<button className="custom-btn" onClick={()=>this.props.history.push('/')} >Back</button>
<form className="subscriber-form" onSubmit={this.onFormSubmitted.bind(this)}>
...............
<button type="submit" className="custom-btn add-btn">Add</button>
</div>
</form>
</div>
</div>)}
}
I think that you need to wrap your AddSubscriber page with withRouter HOC
class AddSubscriber extends React.Component{
...some-code....
}
export default withRouter(AddSubscriber)
you need navigation logic (this.props.history.push("/"))
to be located a addScubscribers page.
(you have it at "homepage" instead)

React Router returns blank page with correct pathing

I'm new to react. I'm following a tutorial, and my code is exactly the same as the tutorial, but the result isn't. Basically, my page routes are returning a blank page. There's no error in the console, so I'm not sure what I'm doing wrong. Here's my code
Homepage.js
import React, { Component } from "react";
import Login from "./Login";
import CreateUser from "./CreateUser";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
Redirect,
} from "react-router-dom";
export default class HomePage extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Router>
<Switch>
<Route exact path="/">
<p>This is the homepage</p>
</Route>
<Route path="/login" component={Login} />
<Route path="/createuser" component={CreateUser} />
</Switch>
</Router>
);
}
}
Login.js Component
import React, { Component } from "react";
export default class Login extends Component {
constructor(props) {
super(props);
}
render() {
return <p>This is the Login Page</p>;
}
}
CreateUser.js Component
import React, { Component } from "react";
export default class CreateUser extends Component {
constructor(props) {
super(props);
}
render() {
return <p>This is the Create User Page</p>;
}
}
App.js
import React, { Component } from "React";
import { render } from "react-dom";
import HomePage from "./HomePage";
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<HomePage />
</div>
);
}
}
const appDiv = document.getElementById("app"); // get 'app' div
render(<App />, appDiv); // place App component into app div
I've tried changing the import "react" code in line 1 to import 'react' among other things.
Any ideas? Thanks!
Try changing the paths to "/login" and "/createuser" in Homepage.js
I am using Django on the backend of the React project I'm working on. The routes were not connected to the url.py file for the url configuration for my Django app.

React router: component not rendering after login

I'm building a website using React and I'm trying to redirect the user to the index page after the login, but my component is not rendering anything, although I'm being redirected and I can see the URL changing from /welcome#/login to /main.
Since I'm not getting any error messages and the webpack is being successfully compiled, I can't see what's wrong anymore.
Any ideas of what could possibly be wrong?
Thank you very much!
Start.js
import React from "react";
import ReactDOM from "react-dom";
import Welcome from "./welcome";
import { App } from "./app";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import reduxPromise from "redux-promise";
import { composeWithDevTools } from "redux-devtools-extension";
import reducer from "./reducer";
const store = createStore(
reducer,
composeWithDevTools(applyMiddleware(reduxPromise))
);
let element;
if (location.pathname === "/welcome") {
element = <Welcome />;
} else {
init(store);
element = (
<Provider store={store}>
<App />
</Provider>
);
}
ReactDOM.render(element, document.querySelector("main"));
Welcome.js
import React from "react";
import Register from "./register";
import Login from "./login";
import { HashRouter, Route, Redirect } from "react-router-dom";
export default class Welcome extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<HashRouter>
<div className="register-wrapper">
<div>
<Route path="/login" component={Login} />
<Route exact path="/" component={Register} />
</div>
</div>
</HashRouter>
);
}
}
Login Component
import React from "react";
import axios from "./axios";
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = { error: false };
this.loginButton = this.loginButton.bind(this);
this.handleChange = this.handleChange.bind(this);
}
loginButton(e) {
e.preventDefault();
axios
.post("/login", this.state)
.then(res => {
if (res.data.success) {
location.replace("/main");
} else {
this.setState({
error: true
});
}
})
.catch(error => console.log(error));
}
handleChange(e) {
this.setState(
{
[e.target.name]: e.target.value
},
() => console.log("this.state:", this.state)
);
}
render() {
return (
<div className="login-main-container">
{this.state.error && <h2>Ops! Something went wrong.</h2>}
<h1 className="login-title">Kathi & Rodolfo</h1>
<h2 className="login-subtitle">Dear guest, please login first</h2>
<div className="login-container">
<form className="login-form">
<label className="label-login" htmlFor="email"> username </label>
<input className="input-login"
name="email"
placeholder="Best Couple You Know"
onChange={this.handleChange}
/>
<label className="label-login" htmlFor="password"> password </label>
<input className="input-login"
name="password"
type="password"
placeholder="Super Loving Password"
onChange={this.handleChange}
/>
<button
className="login-button"
onClick={this.loginButton}
>
Login
</button>
</form>
</div>
<h4 className="login-info">Information about username and password can be found on the Save The Date card</h4>
</div>
);
}
}
Index Component (Main)
import React from "react";
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state ={ error: false};
}
render () {
return (
<div className="main-container">
<header>
<p>the wedding</p>
<p>rpsv</p>
<p>contact us</p>
<p>wedding gift</p>
</header>
{this.state.error && <h2>Ops! Something went wrong.</h2>}
<div className="save-the-date-img">
<h1>Save The Date</h1>
</div>
</div>
);
}
}
App.js
import React from "react";
import { BrowserRouter, Route, Link } from "react-router-dom";
import Main from "./main";
export class App extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<BrowserRouter>
<div>
<Route exact path="/main" Component={Main}/>
</div>
</BrowserRouter>
);
}
}
location.replace("/main");
I think this line is wrong in your code.
While you are using React, you'd rather use react-router-dom's functionality than browser built-in feature.
Change the line to this.props.history.push('/main')
Give your file structure. Your component Login is not in BrowserRouter, but must be. Check the official sample: https://reacttraining.com/react-router/web/guides/quick-start.
instead of
location.replace("/main");
use
history.push("/main")

How to properly define Higher Order Component in reactjs?

I am trying to learn HOC in reactjs and trying to understand this basic example..
I have 3 files named First.js, Second.js and App.js. Now how I need to define those files so that computation done in first file should be accessible to second file.
App.js
import React, { Component } from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import First from './First';
import Second from './Second';
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path='/' component={First}/>
<Route exact path='/Second' component={Second}/>
</Switch>
</Router>
);
}
}
export default App;
First.js
import React, {Component} from 'react';
import {Link} from 'react-router-dom';
import Second from './Second';
class First extends Component{
constructor(props){
super(props);
this.state={
number : 1,
};
}
increment = event => {
this.setState({
number : this.state.number + 1
});
}
decrement = event => {
this.setState({
number : this.state.number - 1
});
}
render(){
return(
<div>
{this.state.number}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<Second number={this.state.number}/>
<Link to='/Second'>Second</Link>
</div>
);
}
}
export default First;
Second.js
import React, {Component} from 'react';
class Second extends Component{
render(){
return(
<div>
{this.props.number}
</div>
);
}
}
export default Second;
I want to access First.js variable in second.js. Give me solution.
Thanks in advance.
Try this
<Route path="/Second" render={()=> (
<div>
100
</div>
)}/>
The above implementation that you have shown isn't of an HOC, rather a simple Route implementation, Since you are rendering the Second component inside of First you would want to render the /second route inside first
import React, { Component } from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import First from './First';
import Second from './Second';
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route path='/' component={First}/>
</Switch>
</Router>
);
}
}
export default App;
First.js
import React, {Component} from 'react';
import {Link} from 'react-router-dom';
import Second from './Second';
class First extends Component{
constructor(props){
super(props);
this.state={
number : 1,
};
}
increment = event => {
this.setState({
number : this.state.number + 1
});
}
decrement = event => {
this.setState({
number : this.state.number - 1
});
}
render(){
return(
<div>
{this.state.number}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<Route path="/Second" render={(props)=> <Second number={this.state.number} {...props}/>} />
<Link to='/Second'>Second</Link>
</div>
);
}
}
export default First;

React JS - Route - Element type is invalid

I'm new to React JS and am trying to implement something similar to the Angular sample application.
I have a table of customers and want to seen the selected customer at the bottom of the table.
I tried the following with react-router-dom:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'bootstrap/dist/css/bootstrap.css';
ReactDOM.render((<BrowserRouter><App /></BrowserRouter>), document.getElementById('root'));
registerServiceWorker();
// App.js
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
import Customers from './components/customers';
import Customer from './components/customer';
export default class App extends Component {
state = {
};
render() {
return (
<React.Fragment>
<Customers />
<Route path={`/customer/:id`} component={Customer} />
</React.Fragment>
);
}
}
// customers.jsx
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Customers extends Component {
state = {
customers: []
};
render() {
return (
<React.Fragment>
<header className="jumbotron"><h1>Customer List</h1></header>
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{this.state.customers.map(c => (<tr key={c.id}><td><Link to={`/customer/${c.id}`}>{c.name}</Link></td><td>{c.address}</td></tr>))}
</tbody>
</table>
<hr />
</div>
<footer className="footer">© 2018</footer>
</React.Fragment>
);
}
async componentDidMount() {
const result = await fetch('http://api.com/customers');
const customers = await result.json();
this.setState({ customers });
console.log(this.state.customers);
}
}
// customer.jsx
import React, { Component } from 'react';
export default class Customer extends Component {
render() {
return (<p>Customer</p>);
};
}
The line in App.js that adds the Route (Route path={/customer/:id} component={Customer}) is causing the error. If I remove that line I can see the table of customers but as soon as I add this line, then I get that error message.
Did I miss something on how this router works?
Thank you.
UPDATE
Event changing App.js to this very simple version causes the error
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
export default class App extends Component {
state = {
};
render() {
return (
<div>
<Route exact path='/' render={() => (<h1>Hello</h1>)} />
<Route exact path='/customer' render={() => (<h1>Customer</h1>)} />
</div>
);
}
}
The full error message is:
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.
change this:
import {Route} from "react-router-dom/Route";
to this:
import Route from "react-router-dom/Route";
Route is a default export when you access it directly: "react-router-dom/Route"
You can use named exports when you import Route from base package
import {Route} from "react-router-dom";
But don't mix the two.
I feel the issue is with back ticks in path. Can you try with this
render() {
return (
<React.Fragment>
<Customers />
<Route path='/customer/:id' component={Customer} />
</React.Fragment>
);
}
OR
render() {
return (
<React.Fragment>
<Customers />
<Route path={'/customer/:id'} component={Customer} />
</React.Fragment>
);
}
Looks like you have a syntax error in the Customer component's render() method which will be causing issue when you attempt to use/render this.
Try the following fix:
export default class Customer extends Component {
render() {
return (<p> Customer</p>); // <-- remove the whitespace in
// closing tag </p> like so
};
}

Categories

Resources