how to move second component in react js? - javascript

I am using react-router.js .I want to show / move to second component / page on click of button using react.js
can I move to second page / component on button click
here is my code
http://codepen.io/naveennsit/pen/RamvLj?editors=1010
var { Router, Route} = ReactRouter
class App extends React.Component {
render() {
return (<Router>
<Route path='/' component={first}></Route>
<Route path='/about' component={second}></Route>
</Router>)
}
}
class second extends React.Component {
render() {
return <label>second component</label>
}
}
class first extends React.Component {
handleClick(){
alert('--')
}
render() {
return <div>
<label>first component</label>
<button onClick={this.handleClick}>MOve to second page</button>
</div>
}
}
React.render( < App / > , document.getElementById('app'))

You can use Link from react-router
var { Router, Route, Link} = ReactRouter
class App extends React.Component {
render() {
return (<Router>
<Route path='/' component={first} />
<Route path='/about' component={second} />
</Router>)
}
}
class second extends React.Component {
render() {
return <label>second component</label>
}
}
class first extends React.Component {
render() {
return <div>
<label>first component</label>
<Link to='/about'><button>MOve to second page</button></Link>
{this.props.children}
</div>
}
}
React.render( < App / > , document.getElementById('app'))
Hope this helps

Related

how to change value of Navbar title in react?

I just learn react, and I try make a website with Bootstrap.
Suppose below picture is my web page.
When I browse a link that path is "/project/react" the top left (value of Navbar title is "React"), then I browse a link that path is "/project/bootstrap" I hope the top left (value of Navbar title is "Bootstrap"). Is that possible?
Because I got the title still show "React".
Thank you
//MyPage.js
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/css/bootstrap.css';
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import MyNavbar from '../components/MyNavbar';
import MyReact from '../components/MyReact';
import MyBootstrap from '../components/MyBootstrap';
let pgName = "My Page"
class MyPage extends Component {
constructor(props) {
super(props);
this.state = {
pageName: pgName
};
}
setPageName = (pageName) => {
pgName = pageName;
}
componentDidMount(){
this.setState({ pageName: pgName });
}
render() {
return (
<div>
<MyNavbar pageTitle={this.state.pageName}/>
<Switch>
<Route path="/project/bootstrap" component={MyBootstrap} render={this.setPageName("Bootstrap")}/>
<Route path="/project/react" component={MyReact} render={this.setPageName("React")}/>
</Switch>
</div>
)
}
};
export default ProjectPage;
//MyNavbar.js
import React from 'react';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import Scrollchor from 'react-scrollchor';
class MyNavbar extends React.Component {
constructor(props) {
super(props);
this.state = {
pageTitle: props.pageTitle
};
}
componentWillReceiveProps(props,state){
this.setState({ pageTitle: props.pageTitle });
}
render() {
return (
<Navbar bg="dark " expand="lg" fixed="top">
<Navbar.Brand href="#home" className="menu-title">{this.state.projectTitle}</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" position="absolute" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto" >
<Scrollchor to="#docs" animate={{ offset: -90, duration: 300 }} className="nav-link">Docs</Scrollchor>
<Scrollchor to="#tutorial" animate={{ offset: -90, duration: 300 }} className="nav-link">Tutorial</Scrollchor>
<Scrollchor to="#blog" animate={{ offset: -90, duration: 300 }} className="nav-link">Blog</Scrollchor>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
export default MyNavbar;
//MyReact.js
import Container from 'react-bootstrap/Container';
import React from 'react';
class MyReact extends React.Component {
render() {
return (
<h1>React</h1>
);
}
}
export default MyReact;
//MyBootstrap.js
import Container from 'react-bootstrap/Container';
import React from 'react';
class MyBootstrap extends React.Component {
render() {
return (
<h1>Bootstrap</h1>
);
}
}
export default MyBootstrap;
You could do something like this.
Pass a callback to the component as a prop
<Route
path="/project/bootstrap"
render={(props) => <MyBootstrap {...props} isAuthed={true} setPageName={this.setPageName.bind(this)} />}
/>
Call the callback when the component is mounted
import Container from 'react-bootstrap/Container';
import React from 'react';
class MyBootstrap extends React.Component {
componentDidMount() {
const { setPageName } = this.props;
if(typeof setPageName === 'function) {
setPageName('Bootstrap');
}
}
render() {
return (
<h1>Bootstrap</h1>
);
}
}
Why calling setPageName in render prop?
according to react document, a render prop is a function prop that a component uses to know what to render.
In this case no need to use render prop just need an onClick function because you just want to change the title of previous rendered Navbar.
Second remember to add setState in your setPageName function, unless DOM would not be aware of state change neither the corresponding props.
Then when you change the pageName state navbar props will react to the change.
<Route path="/project/react" component={MyReact} onClick={() => setPageName (someValue)} />
setPageName = (newPageName) =>{ setState({pageName : newPageName }) }
wish it will help
This may not be correct and is untested, but have you tried this?:
<Route path="/project/bootstrap" component={MyBootstrap} render={() => this.setPageName("Bootstrap")}/>
<Route path="/project/react" component={MyReact} render={() => this.setPageName("React")}/>
I think this is more likely to work, that way your setPageName function is only running on render.

How to pass the state of the page to other React?

I want to know how I can pass a status from one page to another page for if used in the other way.
My first page Body.js (Which I handle the state):
import React from 'react';
import './Body.css';
import axios from 'axios';
import { Link } from "react-router-dom";
import User from './User';
class Body extends React.Component {
constructor (){
super();
this.state ={
employee:[],
employeeCurrent:[],
}
}
componentDidMount(){
axios.get('http://127.0.0.1:3004/employee').then(
response=>this.setState({employee: response.data})
)
}
getName = () => {
const {employee} = this.state;
return employee.map(name=> <Link className='link' to={`/user/${name.name}`}> <div onClick={()=>this.add(name)} key={name.id} className='item'> <img className='img' src={`https://picsum.photos/${name.name}`}></img> <h1 className='name'> {name.name} </h1></div> </Link>)
}
add = (name) => {
const nam = name;
this.state.employeeCurrent.push(nam)
console.log(this.state.employeeCurrent)
}
render(){
return(
<div className='body'>
{this.getName()}
</div>
)
}
}
export default Body;
My second page which I want to get the state called employeeCurrent:
import React from 'react';
import Header from './Header';
import Body from './Body';
class User extends React.Component {
constructor (props){
super(props);
this.props ={
employeeCurrent:[],
}
}
render(){
return(
<div >
{this.props.employeeCurrent}
</div>
)
}
}
export default User;
I'm using the React Router, it looks like this:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import './App.css';
import Home from './Home';
import User from './User';
const AppRouter = () => (
<Router>
<div className='router'>
<Route exact path="/" component={Home}/>
<Route path="/user/:id" component={User}/>
</div>
</Router>
);
export default AppRouter;
My project is:
Home page, where you have users, obtained from the API, all users have attributes (name, age, city and country). Saved in employeeCurrent variable:
What I want is: grab these attributes from the clicked user and play on the user page:
Someone would can help me PLEASE?????
Like I explained earlier, you need to lift the state up:
AppRouter (holds the state and passes it to children)
class AppRouter extends React.Component {
state = {
employeeCurrent: [],
employee: []
};
componentDidMount() {
axios
.get("http://127.0.0.1:3004/employee")
.then(response => this.setState({ employee: response.data }));
}
add = name => {
this.setState(prevState => {
const copy = prevState.employeeCurrent.slice();
copy.push(name);
return {
employeeCurrent: copy
};
});
};
render() {
return (
<Router>
<div className="router">
<Route
exact
path="/"
render={props => (
<Home
{...props}
add={this.add}
employee={this.state.employee}
currentEmployee={this.state.currentEmployee}
/>
)}
/>
<Route
path="/user/:id"
component={props => (
<User
{...props}
employee={this.state.employee}
currentEmployee={this.state.currentEmployee}
/>
)}
/>
</div>
</Router>
);
}
}
Body and User (receive parent state as props together with updater functions):
class Body extends React.Component {
getName = () => {
const { employee, add } = this.props;
return employee.map(name => (
<Link className="link" to={`/user/${name.name}`}>
{" "}
<div onClick={() => add(name)} key={name.id} className="item">
{" "}
<img
className="img"
src={`https://picsum.photos/${name.name}`}
/>{" "}
<h1 className="name"> {name.name} </h1>
</div>{" "}
</Link>
));
};
render() {
return <div className="body">{this.getName()}</div>;
}
}
class User extends React.Component {
render() {
// you will need to map employeeCurrent somehow
return <div>{this.props.employeeCurrent}</div>;
}
}

How to pass component reference to routes component in react

In react i want to pass a reference of component to routes component . But when i route to path such as '/' it re render the passed component so starts with 0 again.
Here is a Link of Working example
https://codesandbox.io/s/884yror0p2
Here is a code, whenever i route from Home-->About the about counter starts with 0.
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
class Dummy extends React.Component {
constructor(props) {
super(props);
this.state = {
c: 0
};
setInterval(() => {
this.setState({ c: this.state.c + 1 });
}, 1000);
}
render() {
return <h1> Counter {this.state.c}</h1>;
}
}
class BasicExample extends React.Component {
constructor(props) {
super(props);
this.state = {
// com: <Dummy /> this technique also not work
};
}
render() {
let com = <Dummy />;
return (
<div>
<Router>
<div>
{com}
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<hr />
<Route
exact
path="/"
// render={() => <Home com={com} />} //this also not work
component={props => <Home {...props} com={com} />}
/>
<Route path="/about"
component={props => <About {...props} com={com} />}
/>
</div>
</Router>
</div>
);
}
}
class Home extends React.Component {
render() {
return (
<div>
{this.props.com}
<h2>Home </h2>
</div>
);
}
}
class About extends React.Component {
constructor(props) {
super(props);
console.log(this.props);
}
render() {
return (
<div>
{this.props.com}
<h2>About</h2>
</div>
);
}
}
ReactDOM.render(<BasicExample />, document.getElementById("root"));
You can’t pass a component by “reference”. However, if you would like to have the same data between all the components you could initialize your state in the parent component (BasicExample) and pass it down or use a state container like Redux.
You can the component down but the component will also go through a mounting process that will invalidate the state that you have stored in it.
If you need to hold the state, it should be stored in the parent component.
const Router = ReactRouterDOM.HashRouter;
const Route = ReactRouterDOM.Route;
const Link = ReactRouterDOM.Link;
class Dummy extends React.Component {
constructor(props) {
super(props);
this.state = {
c: props.c || 0
};
}
componentWillReceiveProps(nextProps) {
if (this.props.c !== nextProps.c) {
this.setState({
c: nextProps.c
});
}
}
render() {
return <h1> Counter {this.state.c}</h1>;
}
}
class BasicExample extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
setInterval(() => {
this.setState(prevState => {
return {
counter: prevState.counter + 1
};
});
}, 1000);
}
render() {
let Com = <Dummy c={this.state.counter} />;
return (
<div>
<h2>Main App</h2>
<Router>
<div>
{Com}
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<hr />
<Route
exact
path="/"
// render={() => <Home com={com} />} //this also not work
render={props => (
<Home {...props} c={this.state.counter} Com={Dummy} />
)}
/>
<Route
path="/about"
render={props => (
<About {...props} c={this.state.counter} Com={Dummy} />
)}
/>
</div>
</Router>
</div>
);
}
}
class Home extends React.Component {
render() {
const Com = this.props.Com;
return (
<div>
<h2>Home </h2>
<Com c={this.props.c} />
</div>
);
}
}
class About extends React.Component {
constructor(props) {
super(props);
}
render() {
const Com = this.props.Com;
return (
<div>
<h2>About</h2>
<Com c={this.props.c} />
</div>
);
}
}
ReactDOM.render(<BasicExample />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.2.0/react-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.2.2/react-router-dom.js"></script>
<div id="root"></div>
Few things to note here are:
Use render property of Route to pass in any props
When you use component (instead of render or children, below) the
router uses React.createElement to create a new React element from the
given component. That means if you provide an inline function to the
component prop, you would create a new component every render. This
results in the existing component unmounting and the new component
mounting instead of just updating the existing component. When using
an inline function for inline rendering, use the render or the
children prop
Use function version of setState to refer to prevState

Reveal a navigation component on one route in React

I have an app with navigation at the top (Home, About, Faq). Only on HOME route I need the menu to be hidden and then reveal onscroll. Navigation is built in App.jsx so it appears on every single page. How do I enable the reveal for just this particular route?
My reveal component
import React, { Component } from 'react';
class NavScroll extends React.Component {
constructor(props){
super(props);
this.state={isHide:false};
this.hideBar = this.hideBar.bind(this)
}
hideBar(){
let {isHide} = this.state
window.scrollY > this.prev?
!isHide && this.setState({isHide:true})
:
isHide && this.setState({isHide:false})
this.prev = window.scrollY;
}
componentDidMount(){
window.addEventListener('scroll',this.hideBar);
}
componentWillUnmount(){
window.removeEventListener('scroll',this.hideBar);
}
render(){
let classHide=this.state.isHide?"hide":""
return <div className={"fixed "+classHide}>
</div>;
}
}
export default NavScroll;
App.jsx
import React, { Component } from 'react';
import NavLink from './global/NavLink.jsx';
import Footer from './global/Footer.jsx';
import NavScroll from './global/NavScroll.jsx';
var App = React.createClass({
render: function(){
return (
<div>
<div>
<NavLink to="/"><img className="logo" alt="HOME"></img></NavLink>
<NavLink to="/about" className="navMenuButton">ABOUT</NavLink>
<NavLink to="/faq" className="navMenuButton">FAQ</NavLink>
</div>
{ this.props.children }
<Footer />
</div>
);
}
});
export default App;
You'll want to check the pathname of the current location. The location is an injected prop of the component rendered for a matched route.
class App extends React.Component {
render() {
const { location } = this.props
return (
<div>
{ location.pathname === '/' ? <HomeNavigation /> : <OtherNavigation /> }
</div>
)
}
}

how to send value one component to another component in react js?

could you please tell me how to send input field value on second component on button click .I have one button and input field in first component.On button click I need to send input field value to second component
here is my code
http://codepen.io/naveennsit/pen/GZbpeV?editors=0010
var { Router, Route,browserHistory } = ReactRouter
class First extends React.Component{
sendValue(){
browserHistory.push('/second');
}
render(){
return (<div>
<input type='text' />
<button onClick={this.sendValue}>send</button>
</div>)
}
}
class Second extends React.Component{
render(){
return <div>second component</div>
}
}
class Main extends React.Component{
render(){
return (
<Router history={browserHistory}>
<Route path='/' component={First}></Route>
<Route path='/second' component={Second}></Route>
</Router>)
}
}
React.render( <Main />,document.getElementById('app'));
browserHistory.push('/')
The best solution would be to create some architecture that would allow you to have a separate state object, change it, and pass changes on to your components. See Flux, or Redux.
For a pinpointed solution, you could use url params:
class First extends React.Component{
sendValue(){
browserHistory.push('/second/' + this.refs.textField.value);
}
render(){
return (
<div>
<input type='text' ref='textField' />
<button onClick={() => {this.sendValue()}}>send</button>
</div>)
}
}
class Second extends React.Component {
render(){
return <div>second component: {this.props.params.test}</div>
}
}
class Main extends React.Component{
render(){
return (
<Router history={browserHistory}>
<Route path='/' component={First}></Route>
<Route path='/second/:test' component={Second}></Route>
</Router>)
}
}
thanks #omerts, by using refs is a best idea and also another way using state and i am also new to react.
var { Router, Route, browserHistory } = ReactRouter
class First extends React.Component{
constructor(props){
super(props);
this.sendValue = this.sendValue.bind(this);
this.setValue = this.setValue.bind(this);
this.state = {
userID: "#nageshwar_uidev"
};
}
setValue(e){
this.setState({
userID: e.target.value
});
}
sendValue(){
//console.log(this.state.userID);
browserHistory.push('/second/'+this.state.userID);
}
render(){
return (
<div>
<input type='text' value={this.state.userID} onChange={this.setValue} />
<button onClick={this.sendValue}>send</button>
</div>
)
}
}
class Second extends React.Component{
render(){
let { userID } = this.props.params;
return <div>The userID from first component is {userID} <a href="#" onClick={()=>browserHistory.push('/')}>back</a></div>
}
}
class Main extends React.Component{
render(){
return (
<Router history={browserHistory}>
<Route path='/' component={First}></Route>
<Route path='/second/:userID' component={Second}></Route>
</Router>)
}
}
React.render( <Main />,document.getElementById('app'));
browserHistory.push('/')
working example at codepen

Categories

Resources