How can I disable some routing components to display? - reactjs

I am making a web site which classified users into the admin and normal ones.
Some routing components should not be displayed like the view of other users' detail unless he is a authenticated user.
Besides, not only it should be displayed to the normal user, it also could not be accessible by the normal user. Where should I modify the code ReactDOM.render(.....) or inside the component ?

You should do it inside the component. ReactDOM.render takes in a React component and a DOM element. It is used to let React take control of the contents of that DOM element by rendering that component within it. Typically, most web apps only have one ReactDOM.render and it is used at the root of the HTML <body>.
What you want to achieve is called conditional rendering. In the example below, The "Edit profile" button will be rendered if this.state.profileBelongsToUser is true. Else it is not rendered in the DOM. You will have to fetch some data to decide the value of that boolean flag.
class Profile extends React.Component {
constructor(props) {
super(props);
// Initialize / set state probably by fetching some data.
this.state = {
profileBelongsToUser: false
};
}
render() {
return (
<div>
<div>
<h1>Profile page</h1>
<p>Name: John Doe</p>
{this.state.profileBelongsToUser ? <button>Edit profile</button> : null}
</div>
</div>
)
}
}

Related

How can I pass props from the current component to another component when the second component is called by url?

We can send data as props from parent component to child component easily but what to do in case of no relationship between two components ?
Please Read my context first so that I can make you understand my problem easily.
In my e commerce react App, when any new user visits my site I want to recommend the user to register. In registration process I keep two steps.
At first I want to take his mobile number from only one input field. when he fills the field and press 'continue' button -
I want to take him another page (component) where from I can take his name, password etc.
Here these two components are independent to each other. When user hits the 'continue' button I am calling a and redirect him to another component.
Now my question is How do I preserve this mobile number in 1st component and send to the 2nd component
[N.B: I don't want the mobile number be visible in the url when calling the 2nd Route]
First Component
export default class FirstComponent extends Component {
render() {
return (
<div>
<input type="text" placeholder="Type Mobile number" />
<Link to={{ pathname: '/signup' }}>
<button>Continue</button>
</Link>
</div>
)
}
}
Second Component
export default class SecondComponent extends Component {
render() {
return (
<div>
<input type="text" placeholder="Type Mobile number" />
</div>
)
}
}
Router
<Route exact path="/signup" render={(props) => {return <SecondComponent />} }/>
You can do it this way:
<Link to={{ pathname: '/signup', state: { number: 3199192910} }}>
<button>Continue</button>
</Link>
And you can access that in your signup component like:
import {withRouter} from 'react-router';
class SecondComponent extends Component {
render() {
// get the number
console.log(this.props.location.state.number)
return (
<div>
<input type="text" placeholder="Type Mobile number" />
</div>
)
}
}
export default withRouter(SecondComponent);
Check out this example, Quotes is what you should be looking at:
On click of button, you can call handleClick function and inside this function you could use push method to send props. This way you would have more control over what representation you want to send your data to other component.
<button onClick={this.handleClick}>continue</button>
handleClick = () => {
this.props.history.push({
pathname: '/signup',
state: { mobile: this.state.mobileNumber }
})
}
Hope that helps!!!
This is where Redux comes into the picture.
Redux is an open-source JavaScript library for managing application state.
So what happens in redux we having something called store which manages the whole state of the application. we dispatch some actions to the stores which calls a function called reducer which mutate the data in the store based on the action that has been dispatched. don't worry if you didn't understand what I said
just watch this 15 min video and you'll completely understand how to use Redux in your application and solve your problem https://www.youtube.com/watch?v=sX3KeP7v7Kg
in order to learn in depth I will recommend you go through the https://redux.js.org/basics/basic-tutorial
now coming back to your problem all you have to do is create a store which saves phone no and when the user clicks on continue button dispatch an action to the reduces to store the phone no and thus your phone no is persisted throughout the application and whenever you want to access the phone just write mapstatetoprops function which is shown in the video to access the data from the store and use it in that component
Hopefully, this will solve your problem
what happens when you don't use redux
of course, you send data as props but what will happen to the props when you refresh the page!!!! the props are lost but when we use redux we can save the data. And you're application works as expected even after refreshed of course they are many other ways to do it

How to build react component can change view type

I'm working a reactjs project have require to build a component can change view type. Like: the component have "view as icon" and "view as list", and have a button to switching eachother. Which the best way to archive that. Thanks
Edit: Sorry for making confuse
This is exactly what i want. As you can see, i have a mediaComponent and i want it can display in 2 different way: as a list and as thumbnail. So how can i do that with react. I don't actually have code for that.
p/s: I have tried conditional rendering but because it's different in render it's require to re-render the component with forceUpdate(). That's don't really look nice. So i hove there are another solution for that.
Render as thumbnail
Render as list
Something like that perhaps:
class MyComponent extends React.Component {
state = {
isList: false
}
toggleList = () => this.setState({ isList: !this.state.isList})
render(){
const { isList } = this.state;
return (
<div>
{isList ? <ListComponent /> : <GridComponent />}
<button onClick={this.toggleList}>Toggle</button>
</div>
)
}
}
export default MyComponent;

Should i use State or Props in this simple ReactJS page?

i'm rebuilding my portfolio with ReactJS as i'm learning this new language and i have 1 question. Should i use state or props only in a website where no content will need to be updated?
This is my main class:
class App extends Component {
state = {
name: 'My name',
job: 'Desenvolvedor Web'
}
render() {
return (
<div className="App">
<Header name={this.state.name} job={this.state.job}/>
</div>
);
}
}
And this is my Header.js
const Header = (props) => {
return(
<div className="Header">
<div className="conteudo text-center">
<img src="" className="rounded img-circle"/>
<h1>{props.name}</h1>
<h2>{props.job}</h2>
</div>
)
}
I guess my entire one page portfolio will follow this structure path, with not a big use of handles and changes in my DOM.
I'm sorry for this noob question, i'm really trying my best to learn React.
You should use both state and props in conjunction with one another. You're using both in your code perfectly fine. State is something that is managed by a component and can be passed down to a child via the props. A simple way of understanding this is that you can pass down the Parent component's state (App) to the child (Header) in the form of props which is an important concept in React.
State is both readable and writable whereas props are read only. Also, any change in the components state triggers a re-render.
Here, your state acts as the top/root level for the data that can be passed down to other components if it needs to be used again.
See these for more info.
What is the difference between state and props in React?
https://flaviocopes.com/react-state-vs-props/
State is for properties of your component that change and in turn cause your component to re-render. If you are only passing data down to read, props are a more appropriate choice.

How to use html and react in Enzyme?

My <Header /> component obtains class collapsed in mobile view. I want to write test that will test mobile view scenario
it('should render mobile view', () => {
const wrapper = mount(
<div style={{width: '700px'}}>
<Header content={headerData} useDOMNodeWidth={true} />
</div>
);
expect(wrapper.find('.header-component').first().hasClass('collapsed')).to.equal(true);
});
After running test I have an AssertionError, so it seems that there is a problem with rendering. I assume that render method only accepts clean react component.
Any idea how I can test it ?
Header component might be rendering mobile view based on some condition. You will have to inject that condition in Header component while/before rendering it.
For eg: I have components on web portals which shows different logos based on customer type. This customer type will be set in my appConfig before I render the component.

In ReactJS + Flux share a save button with many tabs

I have an strucure in a ReactComponent like
class MyComponent extends React.Component {
render() {
return (
<div class="row">
<MyMenuComponentTab></MyMenuComponentTab>
<Tab1></Tab1>
<Tab2></Tab2>
<Tab3></Tab3>
</div>
<div class="row">
<button onClick={this.handleButton}>SAVE</button>
</div>
)
}
}
In every tab you can create an independent entity in the backend, and every tab component is related with his own Store and Action in FLUX.
My question is if it's possible to makes the save button contextual? So if you press that button, it can handle in the function "handleButton" Action and Store is related.
The simplest alternative is to have embebed the save button in every tab, but isn't possible because of graphical design restrictions.
You could keep track of the active tab in the state of your MyComponent. Then, you could pass a callback to each Tab that changes the state to reflect which tab is active. That way, your handleButton function would only need to access this.state.activeTab to handle the save action in context.

Resources