I have this particular code that shows a list of questions and buttons for each of it. When I click the button, it will show the specific answer to the question. My problem is, I have a bunch of questions and when i click the button, it will show all of the answer instead of the specific answer to that question.
Here is the code
class App extends React.Component {
constructor(){
super()
this.state = {
answer: [],
isHidden: true
}
this.toggleHidden = this.toggleHidden.bind(this)
}
componentWillMount(){
fetch('http://www.reddit.com/r/DrunkOrAKid/hot.json?sort=hot')
.then(res => res.json())
.then( (data) => {
const answer = data.data.children.map(obj => obj.data);
this.setState({answer});
})
}
toggleHidden(){
this.setState({isHidden: !this.state.isHidden})
}
render(){
const answer = this.state.answer.slice(2)
return <div>
<h1>Drunk or Kid</h1>
{answer.map(answer =>
<div key={answer.id}>
<p className="title">{answer.title}</p>
<button onClick={this.toggleHidden}>Answer</button>
{!this.state.isHidden && <Show>{answer.selftext}</Show>}
</div>
)}
</div>
}
}
const Show = (props) => <p className="answer">{props.children}</p>
And here is the link to the codepen
Here is a Codepen based on my suggestion:
The basics of the child component would be:
class Question extends React.Component {
// Set initial state of isHidden to false
constructor() {
super();
this.state = {
isHidden: false
}
}
// Toggle the visibility
toggleHidden() {
this.setState({
isHidden: !this.state.isHidden
});
}
// Render the component
render() {
const { answer } = this.props;
return (
<div key={answer.id}>
<p className="title">{answer.title}</p>
<button onClick={ () => this.toggleHidden() }>Answer</button>
{this.state.isHidden && <Show>{answer.selftext}</Show>}
</div>
);
}
}
Then you would map over it within the parent component as:
answer.map(answer =>
<Question answer={answer} key={answer.id} />
)
Another option is to add a state that save opened answer id, then checking if specific answer in that state or not.
let's see in action
class SomeComponent extends React.Component {
constructor(props){
super(props)
this.state = {
opened: []
}
this.toggleShowHide = this.toggleShowHide.bind(this)
}
toggleShowHide(e){
const id = parseInt(e.currentTarget.dataset.id)
if (this.state.opened.indexOf(id) != -1){
// remove from array
this.setState({opened: this.state.opened.filter(o => o !== id)})
} else {
this.setState({opened: [...this.state.opened, id]})
}
}
render(){
return <ul>
{ this.state.answers.map(ans => (
<li key={ans.id} data-id={ans.id}>
question
<button onClick={this.toggleShowHide}>show answer</button>
<span
style={{ display: this.state.opened.indexOf(ans.id) !== -1 ? 'block' : 'none' }}>answer</span>
</li>
))}
</ul>
}
}
Here is video in action https://www.youtube.com/watch?v=GJsPEsckB4w
Related
I am trying to implement a side navigation bar changing the width to show and hide the side navbar. Anyhow, I cannot make the openNav function to work. If I set the initial state to 250 px it shows the navbar and the close function works (it's setting the width to 0). Why the Menu button is not working? What am I missing?
class SideNav extends Component {
constructor(props){
super(props);
this.state = {
navwidth: 0
};
this.openNav = this.openNav.bind(this)
this.closeNav = this.closeNav.bind(this)
}
openNav() {
this.setState({
navwidth: '250 px'
});
}
closeNav() {
this.setState({
navwidth: 0
});
}
render(){
return(
<>
<button onClick={this.openNav}>Menu</button>
<div id="mySidenav" className='sidenav' style={{width: `${this.state.navwidth}`}}>
<a className="closebtn" onClick={this.closeNav}>×</a>
Find data
Visualize Data
About
</div>
</>
)
}
}
class Header extends Component {
render(){
return(
<SideNav/>
)
}
}
export default Header;
Modified your code,
class SideNav extends Component {
constructor(props) {
super(props);
this.state = {
navwidth: 0
};
}
openNav = () => {
this.setState({
navwidth: '250px'
});
}
closeNav = () => {
this.setState({
navwidth: '0px'
});
}
render = () =>
<>
<button onClick={this.openNav}>Menu</button>
<div id="mySidenav" className='sidenav' style={{ width: this.state.navwidth }}>
<a className="closebtn" onClick={this.closeNav}>×</a>
Find data
Visualize Data
About
</div>
</>
}
250 px should be 250px. You also don't need to use a templated string here:
`${this.state.navwidth}`
The simpler:
this.state.navwidth
is valid.
I'm trying to make a toggle content button with React. But I can only get it to open, not to close when I click on it again. Can someone please take a look and let me know what I need to change within the code to accomplish it?
Here's what I have so far:
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
activeLocation: 0,
}
}
changeActiveLocation = (activeLocation) => {
this.setState({
activeLocation: activeLocation,
});
}
render() {
const activeLocation = company.locations[this.state.activeLocation];
return (
{company.locations.map((location, index) => (
<div className="test-item">
<div className="test-item-container" onClick={() => {this.changeActiveLocation(index)}}>
<div className="test-item-header">
<h3>Text goes here!</h3>
<a><FontAwesomeIcon icon={(this.state.activeLocation === index) ? 'times' : 'chevron-right'} /></a>
</div>
</div>
</div>
))}
)
}
}
Thank you!
You're setting the active location to be the same location that you've clicked already so the this.state.activeLocation === index is always true. I would refactor the locations to their own component with an isOpen state value that gets updated when the location is clicked. So like the following:
// test class
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
activeLocation: 0,
}
}
changeActiveLocation = (activeLocation) => {
this.setState({
activeLocation: activeLocation,
});
}
render() {
const activeLocation = company.locations[this.state.activeLocation];
return (
{company.locations.map((location, index) => (
<LocationItem location={location} onClick={() => this.changeActiveLocation(index)} />
))}
)
}
}
// LocationItem
class LocationItem extends React.Component {
state = { isOpen: false };
handleClick = () => {
this.setState(prevState => { isOpen: !prevState.isOpen});
// call parent click to set new active location if that's still needed
if(this.props.onClick) this.props.onClick;
}
render() {
return <div className="test-item">
<div className="test-item-container" onClick={this.handleClick}>
<div className="test-item-header">
<h3>Text goes here!</h3>
<a><FontAwesomeIcon icon={(this.state.isOpen ? 'times' : 'chevron-right'} /></a>
</div>
</div>
</div>
}
}
I have a page contains multiple Bootstrap Cards and each card is a component and each card footer is also a component. Card Footer contains buttons. When you click on a button, drop down will be opened like below
At any point of time when I click on a button, other drop downs should be in closed state. But its happening like this...
Requirement: One more thing is when I click on the same button, the respective drop down should be closed.
Requirement: When I click on any item inside drop down the respective drop down should be closed
My Architecture is like below
HOME PAGE COMPONENT CODE -START
class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
activatedIdStoredInParent: ""
};
}
toggleCountersMenu = (name) => {
var name1 = name;
this.setState((prevState) => {
return {
activatedIdStoredInParent: name1
}
});
}
render() {
const products = this.state.items.map((item, index) => {
return <div>
<Card
product={item}
activatedIdStoredInParent={this.state.activatedIdStoredInParent}
toggleCountersMenu={this.toggleCountersMenu}
>
</Card>;
</div>
});
return (
<div>
<div className="card-columns">
{products}
</div>
</div >
);
}
}
export default HomePage;
HOME PAGE COMPONENT CODE - END
CARD COMPONENT CODE - START
class Card extends React.Component {
handleActionClick = (name) => {
this.props.toggleCountersMenu(name);
}
render() {
return (
<div key={this.props.product.name}>
<CardHeader product={this.props.product} />
<CardBody product={this.props.product} />
<CardFooter
product={this.props.product}
onActionItemClick={this.handleActionClick}
activatedIdStoredInParent={this.props.activatedIdStoredInParent}
/>
</div>
);
}
}
export default Card;
CARD FOOTER COMPONENT CODE - START
class CardFooter extends React.Component {
handleActionItemClick = (name) => {
this.props.onActionItemClick(name);
}
render() {
console.log('Card Footer Drop Down comp rendered');
return (
<div className=" card-footer text-center">
<ButtonDropdown text="F" className="danger"
product={this.props.product}
onActionItemClick={this.handleActionItemClick}
activatedIdStoredInParent={this.props.activatedIdStoredInParent}
></ButtonDropdown>
</div>
);
}
}
export default CardFooter;
ButtonDropdown COMPONENT CODE - START
class ButtonDropdown extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
show: ' none',
localActivatedId: 'none'
}
}
toggleOpen = (e) => {
var name = e.target.name;
this.setState((prevState, props) => {
var item = {
localActivatedId: name
}
if (props.activatedIdStoredInParent === name) {
if (prevState.show === ' show') {
item.show = ' none';
}
else {
item.show = ' show';
}
}
return item;
});
this.props.onActionItemClick(name);
}
numberClick = (e) => {
var qty = e.target.innerText;
this.setState((prevState, props) => {
var item = {
show: ' none'
}
return item;
});
}
render() {
return (
<div className="btn-group" >
<button type="button" className={`btn btn-${this.props.className} mr-1`} name={this.props.product.name + '$$' + this.props.text} onClick={this.toggleOpen}>
{this.props.text} (classAdded={this.state.show})
</button>
<div className={`dropdown-menu ${this.state.show}`}>
<span className="dropdown-item cursor-pointer " onClick={this.numberClick}>
-1
</span>
<span className="dropdown-item cursor-pointer" onClick={this.numberClick}>
-2
</span>
</div>
</div>
);
}
}
export default ButtonDropdown;
When I add multiple buttonDropdown components in Card Footer the end product is like this. How can I close other dropdowns.
I would like to know is my architecture is correct.. I am not using Redux/Flux etc..
You can use the componentDidUpdate lifecycle, in order to update your state's property that is opening the dropdown.
I don't know if it's the open or show property that displays the content of the dropdown but here's my logic.
class ButtonDropdown extends React.Component {
constructor(props) {
super(props);
this.state = {
//
};
}
componentDidUpdate(prevProps) {
const name = this.props.product.name + '$$' + this.props.text;
if (prevProps.activatedIdStoredInParent !== this.props.activatedIdStoredInParent && this.props.activatedIdStoredInParent !== name) {
this.closeDropDown();
}
}
closeDropDown = () => this.setState({ isOpen: false });
toggleOpen = (e) => {
//
}
numberClick = (e) => {
//
}
render() {
//
}
}
export default ButtonDropdown;
I have multiple buttons on my screen and and inside same container I have another label, on click I want to show the label and then hide after few seconds.
I am controlling through this.state problem is when event fires it shows all labels and then hides all. I found few solutions like assign ids etc and array for buttons.
But issue is there can be unlimited buttons so thats not the way to go to set state for each button. Or if there is any other possible way.
export default class App extends React.Component {
constructor(props) {
super();
this.state = {
visible: false
}
}
_handleClick = () => {
this.setState({
visible: !this.state.visible
});
setTimeout(() => {
this.setState({
visible: false
});
},2000);
}
render() {
return (
<div>
<button onClick={this._handleClick}>Button 1</Text></button>
{this.state.visible && <span style={styles.pic}>
Pic
</span>
}
</div>
<div>
<button onClick={this._handleClick}>Button 2</Text></button>
{this.state.visible && <span style={styles.pic}>
Pic
</span>
}
</div>
<div>
<button onClick={this._handleClick}>Button 3</Text></button>
{this.state.visible && <span style={styles.pic}>
Pic
</span>
}
</div>
</div>
);
}
}
You need each button to have its own state... So make each button a Component!
class App extends React.Component {
render() {
return <div>
<Button>1</Button>
<Button>2</Button>
<Button>3</Button>
<Button>4</Button>
</div>
}
}
class Button extends React.Component {
constructor(props) {
super();
this.state = {
visible: false
}
}
_handleClick = () => {
this.setState({
visible: !this.state.visible
});
setTimeout(() => {
this.setState({
visible: false
});
}, 2000);
}
}
If there are unlimited buttons, then you can set the state like this regarding which button is clicked.
_handleClick = (id) => {
this.setState({ [id]: true })
}
id will be the unique id of each button.
Here is a simple example to show how to set the state.
https://codesandbox.io/s/k38qyv28r
I am working on a quiz in react. I want to show one question and their choices at the same time at the page.
Such as :
"question": "When the C programming language has first appeared?",
a.)1970
b.)1971
c.)1972
d.)1973
This is what I have done so far:
import React from 'react'
import axios from 'axios'
class QuizApp extends React.Component {
constructor(props) {
super(props);
this.state = {entered: false, correct: 0, wrong: 0}
}
state = {
questions: [],
choic: []
};
componentDidMount() {
axios.get("http://private-anon-c06008d89c-quizmasters.apiary-mock.com/questions").then((response) => {
const questions = response.data;
this.setState({questions});
const choic = response.data;
this.setState({choic});
console.log(response);
})
}
nickChange = (event) => {
this.setState({username: event.target.value});
};
cleanPage = () => {
this.setState({
entered: true
})
};
render() {
if (!this.state.entered) {
return (
<div>
<form target="_self" id="firstPage">
<input type="text" value={this.nick} onChange={this.nickChange}/>
<input type="submit" value="Start" name="cleanPage" onClick={this.cleanPage}/>
</form>
</div>
)
}
else {
return (
<div>
<ul>
{this.state.questions.map(que => <li>{que.question} </li>)}
{this.state.choic.map(cho => <li>{cho.choices.choice} </li>)}
</ul>
</div>
)
}
}
}
simplify set state in response
const { questions, choices } = response.data;
this.setState({questions, choices});
In render do like this (Assuming each question has corresponding array of choices in that index):
{this.state.questions.map((que, index) => {
<React.Fragment>
<li>{que.question} </li>
<ul>
{choices[index].map(choice => <li>{choice}</li>)
</ul>
<React.Fragment
})}
style the elements as needed