reactjs checkboxlist component - Updating state changes in parent - javascript

I have a bunch of checkbox-list requirements. I will explain in detail. I have a bunch of languages say:
var languages = ["English", "German", "French", "Spanish", "Mandarin", "Tamil"]
I have a parent component which has a form where I have four sections, Say:
class Page extends React.Component {
render() {
return (
<form>
<h1>CanSpeak</h1> <chkboxlist someProp="speak" />
<h1>CanSpeak</h1> <chkboxlist someProp="read" />
<h1>CanSpeak</h1> <chkboxlist someProp="write" />
<h1>CanSpeak</h1> <chkboxlist someProp="understand" />
<button
onClick={e => {
console.log("Need the various chkboxlist values here");
e.preventDefault();
}}
>
Save
</button>
</form>
);
}
}
I want the chkboxlist component to keep track of the list of selected languages in each section and make them available in the "Save" button click handler. I wish to keep track of the state changes (list of selected languages under each section) in the "Page" component.
I do not want to use redux or some such external state management.
Now what is the way to create this chkboxlist component such that the state changes can be tracked in the parent Page component ? Are there any existing components which will fit this requirement and is used widely in the react ecosystem without having to reinvent the wheel ?

I don't know if pulling in a seperate component would be really useful - as it's only a really tiny piece of functionality.
Working fiddle here:
https://jsbin.com/tusakexire/edit?html,js,output
You could do something like:
class Chkboxlist extends React.Component {
constructor(props) {
super(props)
this.state = {}
props.values.map((v, i) => {
this.state[v] = false
})
}
onChange(key, value) {
this.setState({ [key]: value }, (state) => {
this.props.onChange(this.state)
})
}
render() {
return (
<div className="list-group-item form-group">
{this.props.values.map((value, i) => (
<div className="checkbox" key={i}>
<label>
<input
onChange={(e) => this.onChange(value, e.target.checked)}
type='checkbox'
value={this.state[value]}
/>
{value}
</label>
</div>
))}
</div>
)
}
}
class Page extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
onChange(name, values) {
this.setState({ [name]: values })
}
render() {
const languages = ["English", "German", "French", "Spanish", "Mandarin", "Tamil"]
return (
<div className="container">
<div className="row">
<form className="form">
<div className="list-group col-xs-6">
<h4>Can Speak</h4>
<Chkboxlist
onChange={(values) => this.onChange('speak', values)}
values={languages}
/>
</div>
<div className="list-group col-xs-6">
<h4>Can Read</h4>
<Chkboxlist
onChange={(values) => this.onChange('read', values)}
values={languages}
/>
</div>
<div className="list-group col-xs-6">
<h4>Can Write</h4>
<Chkboxlist
onChange={(values) => this.onChange('write', values)}
values={languages}
/>
</div>
<div className="list-group col-xs-6">
<h4>Can Understand</h4>
<Chkboxlist
onChange={(values) => this.onChange('understand', values)}
values={languages}
/>
</div>
<button
className="btn btn-primary"
onClick={(e) => {
console.log(this.state);
e.preventDefault();
}}
>
Save
</button>
</form>
</div>
</div>
);
}
}
ReactDOM.render(<Page />, document.getElementById('app'))

Related

Tranfser props to sibling component

Instead of% username%, I would like the current name and name to be displayed in the modal title
user's surname. I can't make this task. I
after solving the problem, give ideas how I can optimize my code.
Code:
class App extends React.Component {
state= {
show: false,
};
showModal = () =>{
this.setState({
show: !this.state.show
});
};
render() {
const users = this.props.data.users;
const userList = users.map(user => <User key={user.id} user={user} onOpen={this.showModal} name={user.name} surname={user.surname}/>)
return (
<div className="container">
{userList}
{this.state.show ? < Modal onClose={this.showModal} show={this.state.show}/> : null}
</div>
)
}
}
class User extends React.Component{
onOpen = () => {
this.props.onOpen && this.props.onOpen();
};
render(){
const {avatar, name, surname, city, country} = this.props.user;
return(
<div className="box">
<img src={avatar} alt="" className="avatar" />
<h3 className="box-title">{`${name} ${surname}`}</h3>
<p className="box-description">{`${city}, ${country}`}</p>
<div className="button-wrap">
<a href="#" className="button" onClick={()=> this.onOpen()} >Report user</a>
</div>
</div>
)
}
}
class Modal extends React.Component {
onClose = () => {
this.props.onClose && this.props.onClose();
};
render() {
if(!this.props.show){
return null;
}
// tak wygląda struktura HTML dla modal boxa
return (
<div className="modal">
<div className="modal-background"></div>
<div className="modal-content">
<div className="box">
<h3 className="modal-title">Report user</h3>
<textarea rows="6"></textarea>
<div className="button-wrap">
<a href="#" className="button button-link" onClick={() => {
this.onClose()}}>Cancel</a>
<a href="#" className="button ml-auto" onClick={()=> alert("ok")}>Report</a>
</div>
</div>
</div>
</div>
)
}
}
ReactDOM.render(<App data={data} />, document.querySelector("#app"))
using state ReportUsr to store the user you want to report changed by function this.ReportUsr in App class then pass function as prop Report to User class to call it OnClick with the value surname for that instance of User component
then Modal component created from App class has CONTENT which is the App.state.ReportUsr
< Modal onClose={this.showModal} show={this.state.show} >{this.state.ReportUsr}</ Modal>
LiveExample
https://h4i1e.csb.app/
Code https://codesandbox.io/s/modern-browser-h4i1e

My component 'Recipe Items' is being rendered in a single column, when the correct one for each row is 5 columns

I have to render a component from an .json file, until then okay, to be able to read and pass the api values ​​to my component ('RecipeItem'). The problem lies in the part of rendering, because the correct one would be the components being in 5 columns instead of only one.
enter image description here
updated codes below !!!
File RecipeItem.js
const RecipeList = ({ searchString }) => {
return(
<div>
{console.log('to aqui')}
<img className="card-img-top img-fluid" src={searchString.thumbnail} alt={searchString.title} />
<div className="card-body">
<h5 className="card-title">{searchString.title}</h5>
<p className="card-text">
<strong>Ingredients: </strong>{searchString.ingredients}
</p>
</div>
</div>
)
}
const RecipeItem = (props) => {
return (
<div className="col-sm-3 mt-4">
<div className="card">
{props.list && props.list.map((searchString, index) =>
<RecipeList searchString={searchString} key={index} />
)}
</div>
</div>
)
}
File App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
searchString: []
};
}
componentDidMount() {
this.setState({ searchString : data.results })
}
render() {
return (
<div className="App">
<Navbar />
<div className="container mt-10">
<div className="row">
<RecipeItem list={this.state.searchString}/>
</div>
</div>
</div>
);
}
}
Is this working ?
class App extends Component {
render() {
return (
<div className="App">
<Navbar />
<div className="container mt-10">
<div className="row">
{RecipesData.results.map(recipe =>
<RecipeItem
title={recipe.title}
ingredients={recipe.ingredients}
source={recipe.href}
thumbnail={recipe.thumbnail} />
)}
</div>
</div>
</div>
);
}
}

How to filter data using react?

I have created search filter but I am not able to type anything in search input why so ? I have created searchTermChanged method but why is it not working ? When user types in input field the projects should get filtered based on title.
Code:
import Projects from '../../data/projects';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
search: '',
projects: Projects
}
}
searchTermChanged = (event) => {
this.setState({ projects: this.state.projects.filter(val =>
val.title.toLowerCase().indexOf(this.state.search.toLowerCase()) > -1 )
})
}
render() {
return (
<div>
<div className="header">
<div className="md-form mt-0 customsearch">
<input className="form-control" type="text" placeholder="Search projects" aria-label="Search"
value={this.state.search}
onChange={e => this.searchTermChanged(e.target.value)}
/>
</div>
</div>
<div class="container-fluid">
<div class="row">
{this.state.projects.map((val,index) => (
<div class="col-3">
<Card title={val.title} by={val.by} blurb={val.blurb}
url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>
</div>
))}
</div>
</div>
</div>
)
}
}
You need to make sure you're making correct use of the state.
import Projects from '../../data/projects';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
search: '',
projects: Projects
}
}
searchTermChanged = (search) => {
this.setState({
//Update the search state here.
search,
//Use the current search state to filter
projects: this.state.projects.filter(val =>
val.title.toLowerCase().indexOf(search.toLowerCase()) > -1 )
}
);
}
render() {
return (
<div>
<div className="header">
<div className="md-form mt-0 customsearch">
<input className="form-control" type="text" placeholder="Search projects" aria-label="Search"
value={this.state.search}
onChange={e => this.searchTermChanged(e.target.value)}
/>
</div>
</div>
<div class="container-fluid">
<div class="row">
{this.state.projects.map((val,index) => (
<div class="col-3">
<Card title={val.title} by={val.by} blurb={val.blurb}
url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>
</div>
))}
</div>
</div>
</div>
)
}
}
I think if you don't need to change the projects you can also do the bellow to simplify your logic:
constructor(props) {
super(props);
this.state = {
search: ''
}
}
render() {
let {search} from this.state;
let myProjects = projects.filter((p) => {
p.title.toLowerCase().indexOf(search.toLowerCase) > -1
});
return (
<div>
<div className="header">
<div className="md-form mt-0 customsearch">
<input className="form-control" type="text" placeholder="Search projects" aria-label="Search"
value={this.state.search}
onChange={e => this.setState({search: e.target.value})}
/>
</div>
</div>
<div class="container-fluid">
<div class="row">
{myProjects.map((val,index) => (
<div class="col-3">
<Card title={val.title} by={val.by} blurb={val.blurb}
url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>
</div>
))}
</div>
</div>
</div>
)
}
You need to user Projects variable directly to filter otherwise filter changes will search on existing state. You need to set search value to refect what is your input
searchTermChanged = (event) => {
console.log(event);
this.setState({
projects: Projects.filter(val =>
val.title.toLowerCase().indexOf(event.toLowerCase()) > -1 ),
search: event <-- here
})
}
stackblitz: https://stackblitz.com/edit/react-fyf7fr
You are not changing the state of "search".
Assuming u have an input like this:
<input type="text" id="whatever" className="whatever" onChange={(event) => props.searchTermChanged(e.target.value)} />
you can change your method searchTermChanged
searchTermChanged = (value) => {
this.setState({search: value});
this.setState({ projects: this.state.projects.filter(val =>
val.title.toLowerCase().indexOf(value.toLowerCase()) > -1 )
});
}
The reason why u use "value" instead of "this.state.search" here "indexOf(value.toLowerCase())" its because setState is asynchronous and you can reach that piece of code with state outdated. And you are sure that "value" has the right value.

React, Conditionally rendering a component based upon communication between a parent and two children components

I am kinda new to React, what I am trying to do is this, I have a parent component that carries the state, and two children that are considered to be the so-called presentational components lets say (X,Y).
So, Component X receives an array of Items as a prop from the parent and render it, Now, the event should be fired on one of the Items in the X component, then the onClick function will be fired, returning the Item.id to the parent, the parent then will filter the items in the state and pass the selected Item to component Y, Now I want Y to be rendered if and only if it successfully received the selected Item from the parent, here is my code.
// PARENT COMPONENT
class Main extends Component {
constructor(props) {
super(props);
this.state = {
dishes: DISHES,
selectedDish: null
}
}
onDishSelect(dishId){
this.setState({ selectedDish : dishId })
}
render() {
return (
<div >
<Navbar dark color="secondary" >
<div className="container">
<NavbarBrand href="/">My Brand</NavbarBrand>
</div>
</Navbar>
<Menu dishes={this.state.dishes}
onClick={(dishId) => this.onDishSelect(dishId)} />
<DishDetails dish={this.state.dishes.filter(dish => dish.id === this.state.selectedDish)[0]} />
</div>
);
}
}
Component X
render() {
const menu = this.props.dishes.map(item => {
return (
<div key={item.id} className="col-12 col-md-5 offset-md-1 mt-3">
<Card onClick={() => this.props.onClick(item.id)}>
<CardImg width="100%" src={item.image} alt={item.name} />
<CardImgOverlay className="ml-5">
<CardTitle >{item.name}</CardTitle>
</CardImgOverlay>
</Card>
</div>
)
});
return (
<div className="container">
<div className="row">
{ menu }
</div>
</div>
);
}
Finally component Y
class DishDetails extends Component {
constructor(props) {
super(props)
}
renderCard(dish) {
if(this.props.dish){
return (
<div className="col-12 col-md-5 offset-md-1 mt-5 ">
<Card>
<CardImg width="100%" src={dish.image} alt={dish.name} />
<CardBody>
<CardTitle>{ dish.name }</CardTitle>
<CardText>{ dish.description }</CardText>
</CardBody>
</Card>
</div>
)
} else {
return(<div></div>)
}
}
renderViews(review){
if(this.props.dish){
return(
<div key={review.id} className="col-12 col-md-5 mt-5">
<Media body className="mt-2">
<p>{review.comment}</p>
<p>{ review.author }, {new Intl.DateTimeFormat('en-US',{year: 'numeric', month:'short', day: '2-digit'}).format(new Date(Date.parse(review.date)))}</p>
</Media>
</div>
)
} else {
return(<div></div>)
}
}
render(){
return(
<div className="row">
{ this.renderCard(this.props.dish) }
{ this.renderViews(this.props.dish.comments) }
</div>
)
}
}
I know the code structure is very messed up, I am just more concerned abou the functionality for now, thanks in advance.
You can find documentation about conditional rendering at https://reactjs.org/docs/conditional-rendering.html
This applies to your code like this
// PARENT COMPONENT
class Main extends Component {
constructor(props) {
super(props);
this.state = {
dishes: DISHES,
selectedDish: null
}
}
onDishSelect(dishId){
this.setState({ selectedDish : dishId })
}
render() {
return (
<div >
<Navbar dark color="secondary" >
<div className="container">
<NavbarBrand href="/">My Brand</NavbarBrand>
</div>
</Navbar>
<Menu dishes={this.state.dishes}
onClick={(dishId) => this.onDishSelect(dishId)} />
{this.state.selectedDish !== null &&
<DishDetails dish={this.state.dishes.filter(dish => dish.id === this.state.selectedDish)[0]} />
}
</div>
);
}
}
In this way, DishDetails is evaluated only when this.state.selectedDish is different from null, e.g. when the event from X has been processed

Passing props from child to parent(without context)

I'm having a little bit of problem with wrapping my head around with passing states into parents. I need to send data from form container to app so that I can show updated states of list in weather info after submit
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Weather App</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<FormContainer label="Name of the city:"/>
<WeatherInfo
nameOfCity={this.state.nameOfCity}
weatherDescription={this.state.weatherDescription}
windSpeed={this.state.windSpeed}
temperature={this.state.temperature}
maxTemperature={this.state.maxTemperature}
minTemperature={this.state.minTemperature}
/>
</div>
);
}
}
export default App;
Form Container
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
cityName: '',
nameOfCity:'',
weatherDescription:'',
windSpeed:'',
temperature:'',
maxTemperature:'',
minTemperature:''
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleCityName = this.handleCityName.bind(this);
}
handleFormSubmit(e) {
e.preventDefault();
const SendForm = {
cityName: this.state.cityName
};
console.log(SendForm);
fetch(`http://api.openweathermap.org/data/2.5/forecast/weather?q=${SendForm.cityName}&units=metric&APPID=********`)
.then(res => res.json())
.then(results => {
this.setState({
nameOfCity: results.city.name,
weatherDescription: results.list[0].weather[0].description,
windSpeed: results.list[2].wind.speed,
temperature: results.list[0].main.temp,
maxTemperature: results.list[0].main.temp_max,
minTemperature: results.list[0].main.temp_min
});
});
}
handleCityName(value) {
this.setState({ cityName: value });
}
render() {
return (
<div>
<form onSubmit={this.handleFormSubmit}>
<label>{this.props.label}</label>
<SearchBar
name="CityName"
type="text"
value={this.state.cityName}
placeholder="search"
onChange={this.handleCityName}
/>
<button type="submit"
className=""
value='Submit'
placeholder="Search" />
</form>
</div>
);
}
}
export {FormContainer};
Search bar component
const SearchBar = (props) => (
<div>
<label>{props.label}</label>
<input name={props.name} type={props.inputType} value={props.value} placeholder={props.placeholder} onChange={(e)=>props.onChange(e.target.value)}/>
</div>
);
export default SearchBar;
and Weather Info component
const WeatherInfo = (props) => (
<div>
<ul>
<li>{props.nameOfCity}</li>
<li>{props.weatherDescription}</li>
<li>{props.windSpeed}</li>
<li>{props.temperature}</li>
<li>{props.maxTemperature}</li>
<li>{props.minTemperature}</li>
</ul>
</div>
);
export default WeatherInfo;
You can pass method to update App state to FormContainer component
class App extends Component {
constructor() {
this.state = {
cityName: '',
nameOfCity:'',
weatherDescription:'',
windSpeed:'',
temperature:'',
maxTemperature:'',
minTemperature:''
};
}
updateInfo(results) {
this.setState({
nameOfCity: results.city.name,
weatherDescription: results.list[0].weather[0].description,
windSpeed: results.list[2].wind.speed,
temperature: results.list[0].main.temp,
maxTemperature: results.list[0].main.temp_max,
minTemperature: results.list[0].main.temp_min
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Weather App</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<FormContainer label="Name of the city:" updateInfo={this.updateInfo.bind(this)}
nameOfCity={this.state.nameOfCity}
/>
<WeatherInfo
nameOfCity={this.state.nameOfCity}
weatherDescription={this.state.weatherDescription}
windSpeed={this.state.windSpeed}
temperature={this.state.temperature}
maxTemperature={this.state.maxTemperature}
minTemperature={this.state.minTemperature}
/>
</div>
);
}
}
export default App;
And call it from FormComponent
class FormContainer extends Component {
constructor(props) {
super(props);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleCityName = this.handleCityName.bind(this);
}
handleFormSubmit(e) {
e.preventDefault();
const SendForm = {
cityName: this.props.cityName
};
console.log(SendForm);
fetch(`http://api.openweathermap.org/data/2.5/forecast/weather?q=${SendForm.cityName}&units=metric&APPID=********`)
.then(res => res.json())
.then(results => {
this.props.updateInfo(results);
});
}
handleCityName(value) {
// Do what you want to do, like resend API request or smth
}
render() {
return (
<div>
<form onSubmit={this.handleFormSubmit}>
<label>{this.props.label}</label>
<SearchBar
name="CityName"
type="text"
value={this.props.cityName}
placeholder="search"
onChange={this.handleCityName}
/>
<button type="submit"
className=""
value='Submit'
placeholder="Search" />
</form>
</div>
);
}
}
export {FormContainer};

Categories