how to hide component is react and show another component? - javascript

could you please tell me how to hide the component in reactJS and show another component?I have one button and text (hello).on button click, I want to hide button as well as text and show another text bye
here is my code
https://codesandbox.io/s/50lj63xvk
showBankDetail = () => {
console.log("====");
this.setState({
validForm: true
});
};
render() {
const validForm = !this.state.validForm;
return { validForm } ? (
<div>
heloo<button onClick={this.showBankDetail}>hide</button>
</div>
) : (
<div>bye</div>
);
}

One way is to put it on a separate variable first
showBankDetail = () => {
console.log("====");
this.setState({
validForm: true
});
};
render() {
const validForm = !this.state.validForm;
let form;
if (validForm) {
form = (<div>
heloo<button onClick={this.showBankDetail}>hide</button>
</div>);
} else {
form = (<div>bye</div>);
}
return ({form});
}

{ validForm } is creating an object with property validForm and value of validForm (e.g. true or false). You can read more about it here. Your code should look like this
showBankDetail = () => {
console.log("====");
this.setState({
validForm: true
});
};
render() {
const validForm = !this.state.validForm;
return validForm ? (
<div>
heloo<button onClick={this.showBankDetail}>hide</button>
</div>
) : (
<div>bye</div>
);
}

There are a few things you should look at. First off you want to toggle the validForm state, so do that in the showBankDetail function. You could return different elements based on validForm, but you can also do it inline. See:
class App extends React.Component {
constructor() {
super();
this.state = {
validForm: false
};
}
showBankDetail = () => {
this.setState({
validForm: !this.state.validForm
});
};
render() {
return (
<div>
{ this.state.validForm ?
<div>heloo</div> :
<div>bye</div>
}
<button onClick={this.showBankDetail}>hide</button>
</div>
)
}
}

Related

How to fix onClick element. ReactJS

I new in ReactJS and i have one few question. I defined function showModal and but console.log() and
this.setState({show:!this.state.show});.
And after that I applied
this function onClick event for div element inside map function.
1st question: When I click on div element showModal work but in console I don't see my console.log.
2nd question: I want to make when you click on one div element it must add/show few new div elements but only for one div element (on which I clicked). But now when I click on one div element it add/show new elements for all div elements which had this showModal function.
How can i fix this
import React, { Component } from "react";
import Modal from '../components/modal/form'
const DEFAULT_QUERY = 'redux';
const PATH_BASE = 'URL which work correct';
class Actions extends React.PureComponent{
constructor(){
super();
this.state = {
result:null,
show:false,
helpId:null
};
this.setSearchTopStories = this.setSearchTopStories.bind(this);
this.showModal = this.showModal.bind(this);
this.handleClickFromParent = this.handleClickFromParent.bind(this);
this.onClose = this.onClose.bind(this);
}
onClose = e => {
this.setState({ show: false});
}
handleClickFromParent = e => {
this.setState({show: !this.state.show});
}
showModal = e => {
console.log('BABE');
this.setState({show: !this.state.show})
};
setSearchTopStories(result) {
this.setState({ result });
};
componentDidMount() {
fetch(`${PATH_BASE}`)
.then(response => response.json())
.then(result => this.setSearchTopStories(result))
.catch(error => error);
};
render(){
const { searchTerm, result } = this.state;
console.log('* Actions Pure*');
console.log(result);
console.log('=');
return(
<div>
{
(result !== null) ?
result.map(
(item,index) =>
<div>
<div onClick={()=>this.showModal()}>{item.name}</div>
<Modal
id = {index}
handleClickFromParent {this.handleClickFromParent}
item = {[item]}
show = {this.state.show}
onClose = {this.onClose}>
YOLO
</Modal>
</div>
)
: null
}
</div>
)
}
}
export default Actions;
While selecting u can pass the item on method, and on click u can set the item value. Please check the below code.
Demo:
https://codesandbox.io/s/stackoverflowmodal-19i36
this.state = {
result: null,
show: false,
selectedItem:null,
helpId: null
};
//
showModal = (selectedItem) => {
this.setState({
show: !this.state.show,
selectedItem
});
};
//
class Actions extends React.PureComponent {
constructor() {
super();
this.state = {
result: null,
show: false,
selectedItem: null,
helpId: null
};
this.setSearchTopStories = this.setSearchTopStories.bind(this);
this.showModal = this.showModal.bind(this);
this.handleClickFromParent = this.handleClickFromParent.bind(this);
this.onClose = this.onClose.bind(this);
}
onClose = e => {
this.setState({
show: false
});
};
handleClickFromParent = e => {
this.setState({
show: !this.state.show
});
};
showModal = selectedItem => {
this.setState({
show: !this.state.show,
selectedItem
});
};
setSearchTopStories(result) {
this.setState({ result });
}
componentDidMount() {
fetch(`${PATH_BASE}`)
.then(response => response.json())
.then(result => this.setSearchTopStories(result))
.catch(error => error);
}
render() {
const { searchTerm, result, selectedItem } = this.state;
return (
<div>
{result && result.length
? result.map((item, index) => (
<div>
<div onClick={() => this.showModal(item)}>{item.name}</div>
</div>
))
: null}
{selectedItem && (
<Modal
id={index}
handleClickFromParent={this.handleClickFromParent}
item={[selectedItem]}
show={this.state.show}
onClose={this.onClose}
>
YOLO
</Modal>
)}
</div>
);
}
}
export default Actions;

How can I display a modal after a delay?

I'm trying to load a modal 2 seconds after the page has been loaded. I tried setting the state on componentDidUpdate but I keep on getting active: undefined The active props determines the visibility of the modal on the page. I tried toggling it to true on browser on the react tool and my modal shows up. I'm just not sure how to load to it 2 seconds after the page loads up.
state = { show: true };
showModal = () => {
this.setState({ show: true });
};
closeModal = () => {
this.setState({ show: false });
};
render() {
const { showModal } = this.state;
return (
<React.Fragment>
....
<Modal.ModalAnimator active={showModal} onClose={this.closeModal}>
<Modal.ModalWithCross
onClose={this.closeModal}
>
<h3>Are you interested in any other Additions?</h3>
<Section>
<p>Hit “notify concierge” and we’ll be in touch shortly.</p>
</Section>
</Modal.ModalWithCross>
</Modal.ModalAnimator>
</React.Fragment>
)
}
When destructuring the state, you write showModal instead of the actual state field name show. So your first lines in the render function should read:
render() {
const { show } = this.state;
return (
<React.Fragment>
...
<Modal.ModalAnimator active={show} onClose={this.closeModal}>
...
Please try this.
state = { show: true };
closeModal = () => {
this.setState({ show: false });
};
componentDidMount() {
setTimeout(() => {
this.setState({ show: true });
}, 2000);
}
render() {
const { showModal } = this.state;
return (
let model = null;
if (this.state.show) {
let model = (
<Modal.ModalAnimator active={showModal} onClose={this.closeModal}>
<Modal.ModalWithCross
onClose={this.closeModal}
>
<h3>Are you interested in any other Additions?</h3>
<Section>
<p>Hit “notify concierge” and we’ll be in touch shortly.</p>
</Section>
</Modal.ModalWithCross>
</Modal.ModalAnimator>
)
}
<React.Fragment>
....
{model}
</React.Fragment>
)
}

Disable div onClick

I have 4 divs that onClick call a function. When the particular div is clicked, I want the other divs to be non-clickable. But until the particular div is clicked, I want them to be clickable. My code:
import React, { Component } from 'react';
class MyApp extends Component {
state = {
div:2
}
handleClick = (id) => {
id==this.state.div?
//disable onClick for all divs :
//do nothing
}
render() {
return (
<div>
<div onClick={()=>this.handleClick(1)}>
1
</div>
<div onClick={()=>this.handleClick(2)}>
2
</div>
<div onClick={()=>this.handleClick(3)}>
3
</div>
<div onClick={()=>this.handleClick(4)}>
4
</div>
</div>
);
}
}
export default MyApp
How do I do this? Am I correct in disabling the click from the handleClick function?
Thanks.
This is another approach I made and I hope it makes sense and helps. let me know if you have any questions
class App extends Component {
constructor(props) {
super(props);
this.state = {
buttonClick: 2,
buttons: [1,2,3,4],
clicked: false
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(id){
console.log('clicked ', id)
this.setState({
buttonClick: id,
clicked: true
})
}
renderInitButtons() {
const {buttons} = this.state;
return buttons.map(button => {
return <div onClick={() => this.handleClick(button)}> {button} </div>
})
}
renderButtonClicked() {
const {buttons, buttonClick} = this.state;
return buttons.map(button => {
if(buttonClick === button) {
return <div onClick={() => this.handleClick(button)}> {button} </div>
}
return <div > {button} </div>
})
}
render() {
const {buttons, buttonClick, clicked} = this.state;
return (
<div>
{
clicked? this.renderButtonClicked(): this.renderInitButtons()
}
</div>
)
}
}
render(<App />, document.getElementById('root'));
While this is more of a semantic argument, you are still firing an event in each div, regardless of its state. You're just deciding whether or not any action should be taken. If you want to make it truly have no behavior, then you have to dynamically add/remove them. The easiest way is to iterate and create the 4 divs, with a conditional to see if an onClick listener should be added
buildDivs() {
return [1,2,3,4].map(id => {
const divProps = {}
if (this.state.div === id) {
divProps.onClick = () => this.handleClick(id)
}
return <div {...divProps} key={id}>{id}</div>
}
}
render() {
return (
<div>
{this.buildDivs}
</div>
)
}
You can add locked to your state and set it to true when you want to lock other divs and return from your function if its true
I would also change the handleClick function to return a new function to keep the code more readable
class MyApp extends Component {
state = {
div: 2,
locked: false
};
handleClick = id => () => {
if (this.state.locked) return;
if (id === this.state.div) {
this.setState({ locked: true });
}
};
render() {
return (
<div>
<div onClick={this.handleClick(1)}>1</div>
<div onClick={this.handleClick(2)}>2</div>
<div onClick={this.handleClick(3)}>3</div>
<div onClick={this.handleClick(4)}>4</div>
</div>
);
}
}
If you don't want to register any handler you can also check if this.state.locked is true and return null to the onClick function
class MyApp extends Component {
state = {
div: 2,
locked: false
};
handleClick = id => {
if (this.state.locked) return null;
return () => {
if (id === this.state.div) {
this.setState({ locked: true });
}
}
};
render() {
return (
<div>
<div onClick={this.handleClick(1)}>1</div>
<div onClick={this.handleClick(2)}>2</div>
<div onClick={this.handleClick(3)}>3</div>
<div onClick={this.handleClick(4)}>4</div>
</div>
);
}
}

How to check if a prop function in React is clicked

I want to do an if statement. When the prop function is clicked(when you press OK button), I want to render ComponentA otherwise I want to render ComponentB.
Component B contains the button OK and I pass to it as a prop the function.
My if condition is not working properly. Any ideas?
My code:
clickButton() {
console.log("yeah");
}
render() {
const {
clickButton
} = this.props;
return this.clickButton ? (
<ComponentA/>
) : (
<ComponentB clickButton={clickButton}/>
);
}
}
Example.propTypes = {
clickButton: PropTypes.func
};
Not sure if this is what you're looking for:
state = { clicked: false }
clickButton = () => {
console.log("yeah");
this.setState({clicked: !this.state.clicked})
}
render() {
const { clicked } = this.state;
return clicked ? (
<ComponentA/>
) : (
<ComponentB clickButton={this.clickButton}/>
);
}
}
If you want the state outside this component:
clickButton = e => {
console.log("yeah");
// so you will edit the value "clicked" passed as prop in the parent component
this.props.clickButton(e)
}
render() {
const { clicked } = this.props;
return cicked ? (
<ComponentA/>
) : (
<ComponentB clickButton={this.clickButton}/>
);
}
}
You need to pass a state value through the component, so the changed event can be caught, here's how
Parent Component
state = {
isButtonClicked: false
}
clickButton = () => {
this.setState({ isButtonClicked: true })
}
render() {
return (
<Child isButtonClicked={this.state.isButtonClicked} clickButton={this.clickButton} />
)
}
Child Component
render() {
const {
isButtonClicked,
clickButton
} = this.props
return this.isButtonClicked ? (
<ComponentA/>
) : (
<ComponentB clickButton={clickButton}/>
)
}
Example.propTypes = {
isButtonClicked: PropTypes.bool,
clickButton: PropTypes.func
}

Input not focusing on componentDidUpdate

I have an input that is disable by default, but when I dispatch an action to enable it, it should become able. I also want this input to become focused, but I am not able to do that. Here is my component:
class UserInput extends Component {
constructor (props) {
super(props);
this.state = { responseValue: '' };
this.responseHandler = this.responseHandler.bind(this);
this.submitAnswer = this.submitAnswer.bind(this);
}
componentDidUpdate (prevProps) {
if (!this.props.disable && prevProps.disable) {
this.userInput.focus();
}
}
responseHandler (e) {
this.setState({ responseValue: e.target.value });
}
submitAnswer () {
this.props.submitUserAnswer(this.state.responseValue);
this.setState({ responseValue: '' })
}
render () {
return (
<div className="input-container">
<input ref={(userInput) => { this.userInput = userInput; }}
className="input-main"
disabled={this.props.disable}
value={this.state.responseValue}
onChange={this.responseHandler}
/>
<button className="input-button" onClick={this.submitAnswer}>{this.props.strings.SEND}</button>
</div>
);
}
}
UserInput.defaultProps = {
strings: {
'SEND': 'SEND',
},
};
UserInput.contextTypes = {
addSteps: React.PropTypes.func,
};
export default Translate('UserInput')(UserInput);
Thanks in advance!
I reckon your problem lies here:
if (!this.props.disable && prevProps.disable) {
this.userInput.focus();
}
this.props.disable will still be its initial value (false) after the update (it's not being updated by a parent component from what I can see) so the call to focus is never invoked.
I ended up doing this, because I needed to also add a placeholder to the disabled input:
class UserInput extends Component {
constructor (props) {
super(props);
this.state = { responseValue: '' };
this.responseHandler = this.responseHandler.bind(this);
this.submitAnswer = this.submitAnswer.bind(this);
}
responseHandler (e) {
this.setState({ responseValue: e.target.value });
}
submitAnswer () {
this.props.submitUserAnswer(this.state.responseValue);
this.setState({ responseValue: '' })
}
render () {
return (
<div className="input-container">
{ this.props.disable
? <div className="disable-input-box">Wait to type your response</div>
: <input
className="input-main"
disabled={this.props.disable}
value={this.state.responseValue}
onChange={this.responseHandler}
autoFocus
/>
}
<button className="input-button" onClick={this.submitAnswer}>{this.props.strings.SEND}</button>
</div>
);
}
}

Categories