Toggle between the visibility of 2 divs in reactjs - html

I have a simple reactjs website hosted on GitHub Pages. It lists articles, something like feeds in reddit. I have an AddArticle requirement, wherein, upon clicking the 'Add Article' button on the bottom of the page, the Div containing this button must become hidden, and a new Div for adding the details of the article(containing 2 text-boxes and a button named 'Submit') must show up. Upon clicking the 'Submit' button, the earlier Div has to reappear with the new Div getting hidden.
The following is the code I currently use(that is incomplete). Please go through it and provide any insight into the problem. Thanks.
class Child extends React.Component {
constructor(props) {
super(props);
this.onClickSubmitButton = this.onClickSubmitButton.bind(this);
this.state = {
showing: false
};
}
onClickSubmitButton(){
console.log('test-2');
this.setState(
{
showing: true
}
);
}
render() {
const { showing } = this.state;
return (
<div id="div_2">
<br/>
<input type="text" placeholder="Add the article title here" className="block_text"></input>
<br/><br/>
<input type="text" placeholder="Add the article text here" className="block_text"></input>
<br/><br/>
<button
type="button"
onClick={() =>
this.onClickSubmitButton()}
>
Submit
</button>
{ showing
? <div>This is visible</div>
: null
}
</div>
);
}
}
export default class AddArticle extends React.Component {
constructor(props) {
super(props);
this.onClickAddButton = this.onClickAddButton.bind(this);
this.state = {
error: undefined,
tempArticle: undefined,
childVisible: false,
parentVisible: true
};
}
onClickAddButton(){
console.log('test-1');
this.setState(
prevState => (
{
childVisible: !prevState.childVisible,
parentVisible: !prevState.parentVisible
}
)
);
}
// this is the render method
render() {
return (
<div id="div_1">
<br/><br/>
<button
type="button"
onClick={() =>
this.onClickAddButton()}
>
Add Article
</button>
{
this.state.childVisible
? <Child />
: null
}
</div>
);
}
}
<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>

Here is a solution. You should had just send prop to the <Child /> component
DEMO

Related

Delete the entire div including subdiv's on clicking the remove button

I am new to reactjs development and I'm trying real hard to delete the entire division including sub divisions on clicking "remove" button. The addition of entire div is working smoothly, but I am not sure how can I perform deletion of entire div on clicking remove button.
class Createloc extends Component {
constructor(props) {
super(props);
this.state = {
count: 1,
rows: [],
}
this.addRow = this.addRow.bind(this)
this.deleteRow = this.deleteRow.bind(this)
}
// divID = nextId();
addRow() {
this.setState({ count: this.state.count + 1 })
console.log(`Increase count: ${this.state.count}`)
};
deleteRow(e) {
// ==> not sure
// console.log("delete");
};
addingDivs() {
let count = this.state.count, uiItems = [];
while (count--)
uiItems.push(
<div className="newHost" id={this.divID}>
<div className="hostInput">
<input type="text" placeholder="Enter Building Name" />
</div>
<div className="hostInput">
<input type="text" placeholder="Enter Employee Name" />
</div>
<div className="hostInput">
<button className="btn btn-danger" type="button" onClick={this.deleteRow}>Remove</button>
</div>
</div>
)
return uiItems;
}
render() {
return (
<form className="form">
<div className="addButton">
<button type="button" onClick={this.addRow}>Add</button>
{this.addingDivs()}
</div>
</form>
)
}
}
export default Createloc;
PS: I have not included the pseudo I tried to delete just to avoid confusion.
I was able to delete the added row as a stack by applying below:
deleteRow(e) {
this.setState({ count: this.state.count - 1 })
};
Thanks!

React js how to show clicked div and delete previous div content

Hello i have a question if some one could help.
I created a react app with tree buttons when i click on every button the code shows and hide text.
But i wanted when i click for example on button 2 the text from button 1 and 3 to be hidden. And the same for every button if i click on button 3 the text from button 1 and 2 to be hidden also.
import React, { useState } from 'react';
export default class Tinfo extends React.Component{
constructor(props){
super(props);
this.state = { show: new Array(3).fill(false) };
this.baseState = this.state
}
resetState = () => {
this.setState(this.baseState)
}
toggleDiv = (index) => {
var clone = Object.assign( {}, this.state.show );
switch(clone[index]){
case false:
clone[index] = true
break;
case true:
clone[index] = false
break;
}
this.setState({ show: clone });
}
render(){
return(
<div>
{ this.state.show[0] && <div id="tinfo"> First Div </div>}
{ this.state.show[1] && <div id="tinfo"> Second Div </div>}
{ this.state.show[2] && <div id="tinfo"> Third Div </div> }
<button onClick={() => this.toggleDiv(0)}>button 1</button>
<button onClick={() => this.toggleDiv(1)}>button 2</button>
<button onClick={() => this.toggleDiv(2)}>button 3</button>
</div>
)
}
}
since only one can be shown, then just reset the state
toggleDiv = index => {
const show = new Array(3).fill(false);
show[index] = true;
this.setState({
show
});
}
although this should now be named showDiv as it sets the state and hides the rest, it's not a toggle.

How do I display text on button click in React.js

Have this code (below) and am trying to display the text at the click of a button in React.js.
Heres the code:
class App extends Component{
render(){
alert=()=>{return(<h1>Hi</h1>)}
return(<div className="App">
<button onClick={this.alert}>Enter</button>
</div>);
}}
export default App;
Any ideas why it's not working...?
If you want to display it in an alert window, you need to call a function to trigger the window.
class App extends Component{
onButtonClickHandler = () => {
window.alert('Hi')
};
render(){
return(<div className="App">
<button onClick={this.onButtonClickHandler}>Enter</button>
</div>);
}
}
However, if you need to show the message in your render, you can use a state to manage that.
class App extends Component{
state = {
showMessage: false
}
onButtonClickHandler = () => {
this.setState({showMessage: true});
};
render(){
return(<div className="App">
{this.state.showMessage && <p>Hi</p>}
<button onClick={this.onButtonClickHandler}>Enter</button>
</div>);
}
}
Source code:
If you need to toggle the text on button click, you just need to update the onButtonClickHandler function to this.setState({ showMessage: !this.state.showMessage });.
It won't display as like that. Here you are calling alert function and returning some JSX. How react will know where to render?. Do it like below.
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
render: false
}
this.alertHi = this.alertHi.bind(this);
}
alertHi() {
this.setState({render: !this.state.render});
}
render() {
return(
<div className="App">
<button onClick={this.alertHi}>Enter</button>
{this.state.render && <h1>Hi</h1>}
</div>
);
}
}
Demo

How to hide a div and replace it with another div in reactjs?

There are 2 divs. div1 and div2.
Initialy, div1 is shown and div2 is hidden.
Onclick of a button, div1 has to be hidden and div2 should be displayed in the place of div1.
Create a state to indicate whether div1 is to be shown or div2 is to be shown. Then, add a onClick handler function to the button. Finally, conditionally render which component is to be shown according to that state.
Code:
class TwoDivs extends React.Component {
state = {
div1Shown: true,
}
handleButtonClick() {
this.setState({
div1Shown: false,
});
}
render() {
return (
<div>
<button onClick={() => this.handleButtonClick()}>Show div2</button>
{
this.state.div1Shown ?
(<div className="div1">Div1</div>)
: (<div className="div2">Div2</div>)
}
</div>
);
}
}
You can achieve it by adding a new property inside component's state. Clicking the button will simply toggle that state, and the component will re-render, due to setState method. Please notice that this will toggle between the two divs. If you only want to show the second one, set the new state like this: this.setState({firstDivIsActive: false}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
firstDivIsActive: true
};
}
render() {
let activeDiv;
if (this.state.firstDivIsActive) {
activeDiv = <div>I am one</div>;
} else {
activeDiv = <div>I am two</div>;
}
return (
<div>
<button
onClick={() => {
this.setState({
firstDivIsActive: !this.state.firstDivIsActive
});
}}
>
Toggle Div
</button>
{activeDiv}
</div>
);
}
}
I would have done like below in simple HTML and JQuery as below:
<input id="DivType" type="hidden" value="div1" class="valid" />
<div id="div1" />
<div id="div2" />
function ToggleDiv() {
var divType = $("#DivType").val();
if (divType === "div1") {
$("#div1").show();
$("#div2").hide();
$('#DivType input').value = "div2";
}
else if (divType === "div2") {
$("#div1").show();
$("#div2").hide();
$('#DivType input').value = "div1";
}
}
ToggleDiv will be called on OnClick event of button.
Not sure whether there is any better way to do it in React.
class ToggleDivs extends React.Component {
state = {
showDiv1: true,
}
handleButtonClick() {
this.setState({
showDiv1: !this.state.showDiv1
});
}
render() {
const { showDiv1 } = this.state;
const buttonTitle = showDiv1 ? 'Div2' : 'Div1';
const div1 = (<div className="div1">Div1</div>);
const div2 = (<div className="div2">Div2</div>);
return (
<div>
<button onClick={() => this.handleButtonClick()}>Show {buttonTitle}</button>
{showDiv1 ? div1 : div2}
</div>
);
}
}

Render view on click Reactjs

I have created a overlay element and I want it to appear when a certain input field is clicked. I'm new to react so it's not clear to me how I should do it.
This is the view that should appear
import React, { Component } from 'react';
import pro_pic from '../../Resources/img/Anon.jpg';
import menu_drop from '../../Resources/img/drop.png';
class QuestionOverlay extends Component {
render() {
return (
<div id="overlay">
</div>
)
}
}
export default QuestionOverlay;
The click event is here
render() {
function popup_ques(e) {
e.preventDefault();
alert("render overlay view");
}
return (
<div className="middle_div">
<input className='post_data_input' placeholder="Ask your question here" ref="postTxt"
onClick={popup_ques}/>
</div>
);
}
So when I click the input field, the overlay I have created should appear instead of the alert I have given.
This is what I would do:
constructor(props) {
super(props);
this.state = {
overlayVisible: false
}
}
render() {
function popup_ques(e) {
e.preventDefault();
this.setState({
overlayVisible: true
});
}
return (
<div className="middle_div">
<input
className='post_data_input'
placeholder="Ask your question here"
ref="postTxt"
onClick={popup_ques}/>
{this.state.overlayVisible && <QuestionOverlay />}
</div>
);
}
Your function has to be pure, so, based on a state you get an UI render, if you want to insert something, you change your state, but your render function remains the same.
However that approach effectively constructs a new overlay every time you show it, if you want to keep the state perhaps it is better to keep the component but change it's rendering:
import React, { Component } from 'react';
class QuestionOverlay extends Component {
render() {
if(!this.props.visible) {
return null
}
return (<div id="overlay"/>)
}
}
export default QuestionOverlay;
And the container:
constructor(props) {
super(props);
this.state = {
overlayVisible: false
}
}
render() {
function popup_ques(e) {
e.preventDefault();
this.setState({
overlayVisible: true
});
}
return (
<div className="middle_div">
<input
className='post_data_input'
placeholder="Ask your question here"
ref="postTxt"
onClick={popup_ques}/>
<QuestionOverlay visible={this.state.overlayVisible}/>
</div>
);
}