I have 5 such list items i.e self , parents , siblings , relative, friend. Clicking on any item , I am adding a class called active-option . Below is my code , what I have done so far. To note , I am a new to React JS.
import React, { Component } from 'react';
import {Grid, Col, Row, Button} from 'react-bootstrap';
import facebook_login_img from '../../assets/common/facebook-social-login.png';
const profilesCreatedBy = ['Self' , 'Parents' , 'Siblings' , 'Relative' , 'Friend'];
class Register extends Component {
constructor(props) {
super(props);
this.state = { addClass: false };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ addClass: !this.state.addClass });
}
render() {
let selectOption = ["option"];
if (this.state.addClass) {
selectOption.push("active-option");
}
return (
<section className="get-data__block" style={{padding: '80px 0 24px 0'}}>
<Grid>
<Row>
<Col sm={10} md={8} mdOffset={2} smOffset={1}>
<p className="grey-text small-text m-b-32"><i>
STEP 1 OF 6 </i>
</p>
<div className="data__block">
<div className="step-1">
<p className="m-b-32">This profile is being created by</p>
<Row>
{profilesCreatedBy.map((profileCreatedBy, index) => {
return <Col className="col-md-15">
<div onClick={this.handleClick} className={selectOption.join(" ")}>
{profileCreatedBy}
</div>
</Col>;
})}
</Row>
</div>
<Row className="text-center">
<Col xs={12} className="text-center">
<Button href="#" bsStyle="primary" className="m-t-96 m-b-16 has-box__shadow" >
Continue
</Button>
</Col>
</Row>
</div>
</Col>
</Row>
</Grid>
</section>
);
}
}
export default Register;
I am using a map function to display all items. I have tried to add a class called active-option to option. But clicking on any item is adding the class to every other item also. (Attached) Any suggestion ? I want to add active-option class to the one where click event happens, not to every other element. Siblings should not contain active-option class. Please help !
You can achieve this with keeping active item id in the state of component, for example:
class Test extends React.Component{
constructor(){
super();
this.state = {
activeId: null
}
this.setActiveElement = this.setActiveElement.bind(this);
}
setActiveElement(id){
this.setState({activeId: id})
}
render(){
return(
<div>
{
[1,2,3,4,5].map((el, index) =>
<div className={index === this.state.activeId? "active" : ""} onClick={() => this.setActiveElement(index)}>click me</div>
)
}
</div>
)
}
}
https://jsfiddle.net/69z2wepo/85095/
Related
I have two different react components placed one after the other in my app named SearchBar and InfiniteScroller;
function App() {
const [searchTerm, setSearchTerm] = useState("");
return (
<div className="App">
<SNavbar></SNavbar>
<MainLogo></MainLogo>
<SearchBar search={setSearchTerm}></SearchBar>
<hr/>
<InfiniteScroller term={searchTerm}/>
<Footer/>
</div>
);
}
The search bar component has its own state where it updates a search term as its input is being edited and it calls the setSearch function of its parent when the button is clicked (the function is passed as a prop in the parent)
function SearchBar(props)
{
const [search,setSearch] = useState("");
return(
<Container className="Search-Bar">
<Row>
<Col>
<InputGroup >
<FormControl
placeholder="What are we making today?"
onChange={event => setSearch(event.target.value)}
/>
<Button onClick={() => props.search(search)}>
Go!
</Button>
</InputGroup>
</Col>
</Row>
</Container>)
}
The search term that is updated by the SearchBar component is passed onto the InfiniteScroller component as a property and is set as the searchTerm field in its state object.
class InfiniteScroller extends React.Component
{
constructor(props)
{
super(props);
this.state =
{
items:[],
page:1,
hasMore:true,
searchTerm:props.term
};
}
render(){
return(
<InfiniteScroll
dataLength={this.state.items.length}
next={this.fetchData}
hasMore={this.state.hasMore}
loader={<h4>Loading...</h4>}
endMessage={
<p style={{ textAlign: 'center' }}>
<b>Yay! You have seen it all</b>
</p>
}
>
<Row>
{this.state.items.map((i, index) => (
<Col key={index} lg="2" md="4" sm="6" xs="12">
<ImageCell className="ImageCell" link = {this.state.items[index].link}> - #{index}</ImageCell>
</Col>
))}
</Row>
</InfiniteScroll>
)
}
}
However when the setSearchTerm function of App.js is triggered by pressing the button on the SearchBar component, the InfiniteScroller does not seem to get updated. As the SearchTerm field of its state still comes up as "undefined" and the component itself does not re-render to represent the change in property.
I want the InfiniteScroller to completely re-render itself and make some API calls to populate itself with content, How can I achieve this?
So far I've tried adding in HTML tags that have the SearchTerm property in them to check if react skips re-rendering components that don't "use" any properties but that has not worked.
The props' change does not make the UI re-rendering but the states' change does.
It has 2 potential ways to fix have a proper UI re-rendering.
For the first one, you can add key attribute to your component that will help you do a trick for re-rendering whenever key gets changed
<InfiniteScroller term={searchTerm} key={searchTerm}/>
The second way, you can update your local states of that component by componentDidUpdate (useEffect in function-based components)
class InfiniteScroller extends React.Component
{
constructor(props)
{
super(props);
this.state =
{
items:[],
page:1,
hasMore:true,
searchTerm:props.term
};
}
//update states according to props change
componentDidUpdate(prevProps) {
if(this.props.searchTerm !== prevProps.searchTerm) {
setState({ searchTerm: this.props.searchTerm })
}
}
render(){
return(
<InfiniteScroll
dataLength={this.state.items.length}
next={this.fetchData}
hasMore={this.state.hasMore}
loader={<h4>Loading...</h4>}
endMessage={
<p style={{ textAlign: 'center' }}>
<b>Yay! You have seen it all</b>
</p>
}
>
<Row>
{this.state.items.map((i, index) => (
<Col key={index} lg="2" md="4" sm="6" xs="12">
<ImageCell className="ImageCell" link = {this.state.items[index].link}> - #{index}</ImageCell>
</Col>
))}
</Row>
</InfiniteScroll>
)
}
}
I have a react application wherein I want to render an array of menu items, and on click, show the expanded menu item's description. The array of menu items is in a separate file dishes.js
The list of menu items are rendered in a Menu component. On clicking, the expanded menu item is rendered through a DishDetail component.
dishes.js
export const DISHES =
[
{...}
]
MenuComponent.js
class Menu extends Component {
constructor (props) {
super (props);
this.state = {
selectedDish: null
}
}
onDishSelect(dish){
this.setState({ selectedDish: dish })
}
render() {
const menu = this.props.dishes.map((dish)=>{
return (
<div key = {dish.id} className="col-12 col-md-5 m-1"> {/* why do we need this key attribute whenever we construct a list of items in react, we need this key attribute When rendering elements on screen, the keys help react identify these elements uniquely */}
<Card onClick = {()=>this.onDishSelect(dish)}>
<CardImg width="100%" src= {dish.image} alt = {dish.name} />
<CardImgOverlay>
<CardTitle> {dish.name} </CardTitle>
</CardImgOverlay>
</Card>
</div>
);
});
return(
<div className="container">
<div className="row">
{menu}
</div>
<div className = "row">
<DishDetail p={this.state.selectedDish} />
</div>
</div>
);
}
}
export default Menu;
DishdetailComponent.js
class DishDetail extends Component {
constructor(props){
super(props);
this.state = {
}
}
render() {
if (p != null){
return(
<div className = "row">
<Card>
<CardImg width="100%" src={p.image} alt={p.name} />
<CardBody>
<CardTitle> {p.name} </CardTitle>
<CardText> {p.description}</CardText>
</CardBody>
</Card>
</div>
);
}
else {
return(
<div> </div>
);
}
}
}
export default DishDetail;
Output
./src/components/DishdetailComponent.js
Line 17:9: 'p' is not defined no-undef
Line 22:40: 'p' is not defined no-undef
Line 22:54: 'p' is not defined no-undef
Line 24:28: 'p' is not defined no-undef
Line 25:27: 'p' is not defined no-undef
Search for the keywords to learn more about each error.
Any help on this issue is greatly appreciated.
You're not defining p in the render function. Did you perhaps mean this.props.p?
class DishDetail extends Component {
constructor(props){
super(props);
this.state = {
}
}
render() {
const { p } = this.props;
if (p != null){
return(
<div className = "row">
<Card>
<CardImg width="100%" src={p.image} alt={p.name} />
<CardBody>
<CardTitle> {p.name} </CardTitle>
<CardText> {p.description}</CardText>
</CardBody>
</Card>
</div>
);
}
else {
return(
<div> </div>
);
}
}
}
export default DishDetail;
I am creating a bar with two dropdown. The second dropdown depends of the selection from the first dropdown. I have 3 Components :
1. Dropdown Bar : Contains FirstDropdown and Second Dropdown
2. FirstDropdown
3. SecondDropdown
Trying to pass State -> Practice that appears in the FirstDropdown Component as props to SecondDropdown Component. Clearly I'm not doing this correctly. Any Help will be appreciate. Thank you in advance!
class DropdownBar extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<div>
<div className="top-bar">
<Row>
<div style={{marginTop: 15, marginBottom:15}}>
<Col span={8}><FirstDropdown practice={this.props.practice} /></Col>
<Col span={8}><SecondDropdown /></Col>
</div>
</Row>
</div>
</div>
)
}
class FirstDropdown extends React.Component {
constructor() {
super();
this.state = {
practices: [
name = 'Jon',
name = 'potato',
name = 'stark',
],
practice: 'stark'
}
}
onChangePractice(value) {
console.log(`selected ${value}`);
this.setState({
practice: value
})
}
render () {
const {practices} = this.state
return (
<div>
<Row>
<div className="First-dropdown">
<Col span={8}><div className="dropdown-title">Research: </div></Col>
<Col span={14}>
<Select
showSearch
style={{ width: '100%' }}
placeholder="Select a Something"
optionFilterProp="children"
onChange={this.onChangePractice.bind(this)}
onFocus={onFocus}
onBlur={onBlur}
onSearch={onSearch}
filterOption={(input, option) =>
option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{practices.map(practice => (
<Option
value={practice}
key={practice}
data-automation={practice.name}
>{practice}</Option>
))}
</Select>
</Col>
</div>
</Row>
</div>
)
}
class SecondDropdown extends React.Component {
constructor(props) {
super(props);
this.state = {
modules: [
name = 'Drogon',
name = 'Rhaegal',
name = 'Viserion',
]
}
}
componentDidUpdate(prevProps) {
console.log(this.props.practice)
if (!equal(this.props.practice, prevProps.practice))
{
this.updatePractice();
}
}
render () {
const {modules} = this.state
console.log(this.props.practice )
let practice = this.props.practice;
if (practice === 'stark') {
return (
<div>
<Row>
<div className="benchmark-dropdown">
<Col span={4}><div className="dropdown-title">Module: </div></Col>
<Col span={16}>
<Select
showSearch
style={{ width: '100%' }}
placeholder="Select Something"
optionFilterProp="children"
onChange={onChange}
onFocus={onFocus}
onBlur={onBlur}
onSearch={onSearch}
filterOption={(input, option) =>
option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{modules.map(item => (
<Option
value={item}
key={item}
>{item}</Option>
))}
</Select>
</Col>
</div>
</Row>
</div>
)
} else {
return <div> NOOOOO </div>
}
}
In order for both dropdowns to have access to the practice prop, you need to lift it up to the DropdownBar's state, and pass down both practice and a way to update practice.
class DropdownBar extends Component {
state = {
practice: '',
}
handlePracticeChange = (value) => {
setState({ practice: value });
}
render() {
return (
<div>
<FirstDropdown
practice={this.state.practice}
onPracticeChange={this.handlePracticeChange}
/>
<SecondDropdown practice={this.state.practice} />
</div>
)
}
}
So, practice only lives in DropdownBar, and the practices array should live in FirstDropdown child.
In FirstDropdown, you should pass props.onPracticeChange to your Select's onChange:
class FirstDropdown extends Component {
render() {
...
<Select
onChange={this.props.onPracticeChange}
...
}
}
From your code example, it looks like Select passes the currently selected value to onChange.
I'd pull the state into the parent.
class MainBar extends React.Component {
state = {
practice: null
};
handleChange = practice => {
this.setState({ practice });
}
render() {
return (
<div className="top-bar">
<Row>
<div style={{marginTop: 15, marginBottom:15}}>
<Col span={8}>
<FirstDropdown
onChange={this.handleChange}
practice={this.state.practice}
/>
</Col>
<Col span={8}>
<SecondDropdown practice={this.state.practice} />
</Col>
</div>
</Row>
</div>
);
}
}
I am trying to show my results from a JSON file only when the search button is clicked. What is the correct way to do it?
Right now as the user types a product the results are show. I have a simple filter, that is filtering the results, but I would like to make that only appear when the button is clicked. I only want to show results when the search button is clicked.
class App extends Component {
constructor(props){
super(props);
this.state = {
value: '',
list: []
}
this.handleChange = this.handleChange.bind(this);
this.handleSearch = this.handleSearch.bind(this);
this.refresh();
}
handleChange(event){
this.setState({ ...this.state, value: event.target.value })
}
refresh(){
axios.get(`${URL}`)
.then(resp => this.setState({...this.state, value: '', list: resp.data}));
}
handleSearch(product){
this.refresh();
}
render(){
return(
<div className="outer-wrapper">
<Header />
<main>
<Container>
<Row>
<Col xs={12} md={12} lg={12} className="pl-0 pr-0">
<SearchBar
handleChange={this.handleChange}
handleToggle={this.handleToggle}
handleSearch={this.handleSearch}
value={this.state.value}
/>
<SearchResultBar
value={this.state.value}
/>
<Filter />
</Col>
</Row>
<ProductList
value={this.state.value}
list={this.state.list}
/>
</Container>
</main>
</div>
)
}
}
export default App;
class Search extends Component {
constructor(props){
super(props);
}
render(){
return(
<div className="search-input">
<InputGroup>
<Input placeholder='Enter Search'
onChange={this.props.handleChange}
value={this.props.value}
/>
<InputGroupAddon className='input-group-append'
onClick={this.props.handleSearch}>
<span className='input-group-text'>
<i className="fa fa-search fa-lg fa-flip-horizontal"></i>
</span>
</InputGroupAddon>
</InputGroup>
</div>
)
}
}
export default Search;
class ProductList extends Component {
constructor(props){
super(props);
this.state = {
}
}
render(){
let filteredSearch = this.props.list.filter(
(product) => {
return product.title.indexOf(this.props.value) !== -1
}
)
return(
<Container>
<Row>
{
filteredSearch.map(item => {
return <Product {...item} key={item._id} />
})
}
</Row>
</Container>
);
}
}
export default ProductList;
As it stands, my list of products is being displayed in the app as soon as it loads. This seems something trivial, but I have been scratching my head in trying to solve it.
You're calling this.refresh() inside the constructor. So it gets run on mount.
Just remove it from the constructor and you should be fine.
I trying to change my state in another component. I have passed the state by props
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
isOpen: false
};
}
<MobileContent isOpen={this.state.isOpen} />
In my MobileContent component i want to change the state when i click on the element.
class MobileContent extends Component {
render() {
if (this.props.isOpen) {
return (
<Grid fluid>
<div className="mobileContent">
<Row center="xs">
<Col xs={12}>
<span className="button">Hello, world!</span>
<span className="close" onClick={this.handleClick} >X</span>
</Col>
</Row>
</div>
</Grid>
);
}
return null;
}
}
export default MobileContent;
Thanks for the help !!
If you want the Child component to notify the parent, then you should pass an additional prop down to the child which is a function. The child can then call that. So in the parent:
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
isOpen: false
};
}
<MobileContent isOpen={this.state.isOpen} onClose={this.handleClick}/>
And in the child:
render() {
if (this.props.isOpen) {
return (
<Grid fluid>
<div className="mobileContent">
<Row center="xs">
<Col xs={12}>
<span className="button">Hello, world!</span>
<span className="close" onClick={this.props.onClose}>X</span>
</Col>
</Row>
</div>
</Grid>
);
}
return null;
}