defaultValue is pulling the last value in React - javascript

If i click on a particular ToDos edit button, its value should be defaulted inside the textarea but everytime the last ToDo is defaulting, can somebody please help, whether using ref is a right choice or something else, then where i m wrong what i'm suppose to do ?
handleEdit() {
e.preventDefault();
.....
}
renderDisplay() {
return(
<div>
{
this.props.listArr.map((list,i) => {
return(
<div key={i} index={i} ref="newText">
<li>{list}
<div>
<button className="btn btn-primary btn-xs glyphicon glyphicon-pencil"
onClick={this.handleEdit.bind(this)}
/>
</div>
<hr/>
</li>
</div>
)})
}
</div>
);
}
renderForm() {
return(
<div>
<textarea className="form-control" defaultValue={this.refs.newText.innerText} rows="1" cols="100" style={{width: 500}}/>
</div>
)
}
render() {
if(this.state.editing) {
return this.renderForm();
}else {
return this.renderDisplay();
}
}
}

First of all you are using an old ref API. You should use this one, where you set the ref to the instance of the class using this with a callback.
<input ref={ref => {this.myInput = ref}} />
And then you can access its value by just referring to this.myInput .
As for your "bug", keep in mind that you are looping over and overriding the ref. so the last ref assignment would be the last item in the array.
this.props.listArr.map((list,i) => {
return(
<div key={i} index={i} ref="newText">
<li>{list}
There will always be 1 newText ref and it will always be the last item in the array.
You should render different ref names according to the item id and then pass the id of the item to the renderForm so it can access the relevant ref.
With that said, i really recommend to extract the todo to a different component as well as the form. I don't see a valid reason to use refs in this case.
Edit
As a follow-up to your comment, here is a small example of how you would use components instead of refs in order to get information from the child like values etc..
class Todo extends React.Component {
onClick = () => {
const { todoId, onClick } = this.props;
onClick(todoId);
}
render() {
const { value, complete } = this.props;
return (
<div
style={{ textDecoration: complete && 'line-through' }}
onClick={this.onClick}
>
{value}
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
todos: [
{ id: '1', value: 'to do this', complete: false },
{ id: '2', value: 'todo that', complete: true },
{ id: '3', value: 'will do it later', complete: false }]
}
}
toggleTodo = (todoId) => {
const { todos } = this.state;
const nextState = todos.map(todo => {
if (todo.id !== todoId) return todo;
return {
...todo,
complete: !todo.complete
}
});
this.setState({ todos: nextState });
}
render() {
const { todos } = this.state;
return (
<div >
{
todos.map((todo) => {
return (
<Todo
complete={todo.complete}
key={todo.id}
todoId={todo.id}
value={todo.value}
onClick={this.toggleTodo}
/>
)
})
}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<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>
<div id="root"></div>

Related

How to get search value into api string

So I have stated learning react and tried to make a project that renders data from an api. I have 2 components, a Search bar and a component that renders the weather.
What I'm trying to do is to get the value from the search bar and concatenate into the api string. I have tried doing this by settings a prop but I am unable accessing it in the weather component.
My questions is: How can I access the search value in a different component
/components/Search.js
class Search extends Component {
state = {
title: '',
};
onChange = (e) => {
this.setState({ title: e.target.value });
};
onSubmit = (e) => {
// e.preventDefault();
this.props.searchValue(this.state.title);
this.setState({ title: '' });
};
render() {
return (
<Mui.Container>
<CssBaseline />
<form
onSubmit={this.onSubmit}
autoComplete='off'
>
<Mui.Input
placeholder='enter place'
value={this.state.title}
onChange={this.onChange}
/>
</form>
</Mui.Container>
);
}
}
Search.propTypes = {
searchValue: PropTypes.func,
};
/components/Weather.js
class Weather extends Component {
state = {
videos: [],
};
componentDidMount = () => {
axios
.get(
'<weather api here>'
)
.then((res) => {
const videosArr = res.data.videos.map((item) => {
return item;
});
this.setState({ videos: videosArr });
});
};
render() {
return (
{this.state.videos.map((video, index) => {
return (
<React.Fragment key={video.id}>
<Mui.Grid item>
<Mui.Paper>
<div>
<img src='./190x107.png' alt='placeholder' />
<div>
<a href={video.url}>{video.title}</a>
</div>
</div>
</Mui.Paper>
</Mui.Grid>
</React.Fragment>
);
})}
);
}
}
I assume there will be a parent component for <Weather /> and <Search />?
If yes then the parent component can have state, and you pass your setState function into the search component, and then you pass the current state into the weather component.
<Weather searchValue="current state from parent" />
class Weather extends React.Component {
constructor(props) {
super(props);
this.state = {
videos: []
};
}
componentDidMount = () => {
axios
.get(`URL?${this.props.searchValue}`)
.then((res) => {
const videosArr = res.data.videos.map((item) => {
return item;
});
this.setState({ videos: videosArr });
});
};
render() {
return (
{this.state.videos.map((video, index) => {
return (
<React.Fragment key={video.id}>
<Mui.Grid item>
<Mui.Paper>
<div>
<img src='./190x107.png' alt='placeholder' />
<div>
<a href={video.url}>{video.title}</a>
</div>
</div>
</Mui.Paper>
</Mui.Grid>
</React.Fragment>
);
})}
);
}
}

Toggle one list item instead of entire list

I am making a card that lists radio stations and when you click on a station a picture drops down for that list item. all data i am pulling from a json.
I have tried building the list in the toggle.js and in the app.js files
app.js-- div with toggle (its all inside a card..many divs)
<div class="card-trip-infos">
<div>
<Toggle />
</div>
<img class="card-trip-user avatar-bordered"/>
</div>
toggle.js render block:
state = {
on: false,
}
toggle = () => {
this.setState({
on: !this.state.on
})
}
render() {
return (
<ul>
<div>
<p>{PostData.radios[0].name}</p>
{PostData.radios.map((postDetail, index) => {
return <div>
<li onClick={this.toggle}>
<span id='radioName'>{postDetail.name}</span> <span id='frequency'>{postDetail.frequency}</span>
</li>
{
this.state.on && <img src='imagesrc'></img>
}
</div>
})}
</div>
</ul>
)
}
}
I dont know what exactly is wrong but i expect to be able to toggle a picture for each list row seperately. i am confused where to iterate over my json and where to plug everything in.
many Thanks!!
Since we don't know your toggle function and all your component we can't make exact suggestions but in order to do what you want here (just toggle the selected item), you have two different approaches.
You can keep the selected state in the component itself.
class App extends React.Component {
state = {
cards: [
{ id: 1, name: "foo" },
{ id: 2, name: "bar" },
{ id: 3, name: "baz" }
],
};
render() {
const { cards } = this.state;
return (
<div>
{cards.map(card => (
<Card
key={card.id}
card={card}
/>
))}
</div>
);
}
}
class Card extends React.Component {
state = {
selected: false
};
handleSelect = () =>
this.setState(state => ({
selected: !state.selected
}));
render() {
const { card } = this.props;
return (
<div
className={this.state.selected ? "selected" : ""}
onClick={this.handleSelect}
>
{card.id}-{card.name}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
.selected {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />
You can keep the selected state in the parent component.
class App extends React.Component {
state = {
cards: [
{ id: 1, name: "foo" },
{ id: 2, name: "bar" },
{ id: 3, name: "baz" }
],
selected: {}
};
handleSelect = id =>
this.setState(state => ({
selected: { ...state.selected, [id]: !state.selected[id] }
}));
render() {
const { cards, selected } = this.state;
return (
<div>
{cards.map(card => (
<Card
key={card.id}
card={card}
handleSelect={this.handleSelect}
selected={selected[card.id]}
/>
))}
</div>
);
}
}
const Card = ({ card, handleSelect, selected }) => {
const handleClick = () => handleSelect(card.id);
return (
<div className={selected ? "selected" : ""} onClick={handleClick}>
{card.id}-{card.name}
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
.selected {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />
Create a component for individual list item, have a state there which will hold a boolean property to tell whether the image is to be shown or not. Render function will look something like this:
render (
return (
<li onClick="this.toggleShowImage()">
<div> {props.data.name} </div>
<div> {props.data.frequency} </div>
{this.state.showImage ? <img src='imageUrl' /> : null }
</li>
)
)
Then in toggle.js iterate through your data and create the list components. The render function will look something like below:
render() {
return (
<ul>
{PostData.radios.map((postDetail, index) => {
return <ListItem key={postDetail.name} data={postDetail} />
})}
</ul>
)
}

Force input's onChange event bubble to parent form with the value stored in the state

EDIT
Sorry for showing wrong use-case. All inputs inside the Form are being passed though this.props.children, and they can be situated at any deep point of the components tree, so the approach of passing the handleChange directly to inputs will not work at all.
Here is code snippet with the reproduction of the problem.
class CustomSelect extends React.Component {
items = [
{ id: 1, text: "Kappa 1" },
{ id: 2, text: "Kappa 2" },
{ id: 3, text: "Kappa 3" }
]
state = {
selected: null,
}
handleSelect = (item) => {
this.setState({ selected: item })
}
render() {
var { selected } = this.state
return (
<div className="custom-select">
<input
name={this.props.name}
required
style={{ display: "none" }} // or type="hidden", whatever
value={selected
? selected.id
: ""
}
onChange={() => {}}
/>
<div>Selected: {selected ? selected.text : "nothing"}</div>
{this.items.map(item => {
return (
<button
key={item.id}
type="button"
onClick={() => this.handleSelect(item)}
>
{item.text}
</button>
)
})}
</div>
)
}
}
class Form extends React.Component {
handleChange = (event) => {
console.log("Form onChange")
}
render() {
return (
<form onChange={this.handleChange}>
{this.props.children}
</form>
)
}
}
ReactDOM.render(
<Form>
<label>This input will trigger form's onChange event</label>
<input />
<CustomSelect name="kappa" />
</Form>,
document.getElementById("__root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="__root"></div>
As you can see, when you type something in default input (controlled or uncontrolled, whatever), form catches bubbled onChange event. But when you are setting the value of the input programmatically (with the state, in this case), the onChange event is not being triggered, so I cannot catch this changes inside the form's onChange.
Is there any options to beat this problem? I tried to input.dispatchEvent(new Event("change", { bubbles: true })) immediately after setState({ selected: input }) and inside it's callback, but there is no result.
I really think the best to do what you try to do is first make sure to control each individual input. Keep those values in state and just working with the onSubmit event from the form. React even recommended this approach here https://reactjs.org/docs/uncontrolled-components.html
In most cases, we recommend using controlled components to implement
forms. In a controlled component, form data is handled by a React
component. The alternative is uncontrolled components, where form data
is handled by the DOM itself.
You can read about controlled here https://reactjs.org/docs/forms.html#controlled-components
If you want to see how I will have made with just control this will have been looks like that https://codesandbox.io/s/2w9qnk8lxp You can see if you click enter the form submit event with the value keep in state.
class CustomSelect extends React.Component {
items = [
{ id: 1, text: "Kappa 1" },
{ id: 2, text: "Kappa 2" },
{ id: 3, text: "Kappa 3" }
];
render() {
return (
<div className="custom-select">
<div>
Selected: {this.props.selected ? this.props.selected.text : "nothing"}
</div>
{this.items.map(item => {
return (
<button
key={item.id}
type="button"
onClick={() => this.props.onChange(item)}
>
{item.text}
</button>
);
})}
</div>
);
}
}
class Form extends React.Component {
state = {
firstInput: "",
selected: null
};
handleSubmit = event => {
event.preventDefault();
console.log("Form submit", this.state);
};
handleInputChange = name => event => {
this.setState({ [name]: event.target.value });
};
handleSelectedChanged = selected => {
this.setState({ selected });
};
render() {
console.log(this.state);
return (
<form onSubmit={this.handleSubmit}>
<label>This input will trigger form's onChange event</label>
<input
value={this.state.firstInput}
onChange={this.handleInputChange("firstInput")}
/>
<CustomSelect
name="kappa"
selected={this.state.selected}
onChange={this.handleSelectedChanged}
/>
</form>
);
}
}
But if you really want your way, you should pass down the handleChange function as a callback to the children and make use of this props as a function when you click on an element. Example here https://codesandbox.io/s/0o8545mn1p.
class CustomSelect extends React.Component {
items = [
{ id: 1, text: "Kappa 1" },
{ id: 2, text: "Kappa 2" },
{ id: 3, text: "Kappa 3" }
];
state = {
selected: null
};
handleSelect = item => {
this.setState({ selected: item });
this.props.onChange({ selected: item });
};
render() {
var { selected } = this.state;
return (
<div className="custom-select">
<input
name={this.props.name}
required
style={{ display: "none" }} // or type="hidden", whatever
value={selected ? selected.id : ""}
onChange={() => {}}
/>
<div>Selected: {selected ? selected.text : "nothing"}</div>
{this.items.map(item => {
return (
<button
key={item.id}
type="button"
onClick={() => this.handleSelect(item)}
>
{item.text}
</button>
);
})}
</div>
);
}
}
class Form extends React.Component {
handleChange = event => {
console.log("Form onChange");
};
render() {
return (
<form onChange={this.handleChange}>
<label>This input will trigger form's onChange event</label>
<input />
<CustomSelect name="kappa" onChange={this.handleChange} />
</form>
);
}
}
If you pass down the function from the form you can trigger it manually. You just need to create the new Event() to suite you needs of info. Since its a prop it will sync if any method changes happen in the parent element.
Since you use props to generate elements within the form you must map them like so. This was the event only gets added to the custom elements.
class CustomSelect extends React.Component {
propTypes: {
onChange: React.PropTypes.func
}
items = [
{ id: 1, text: "Kappa 1" },
{ id: 2, text: "Kappa 2" },
{ id: 3, text: "Kappa 3" }
]
state = {
selected: null,
}
handleSelect = (item) => {
this.setState({ selected: item });
this.props.onChange.self(new Event('onchange'))
};
render() {
var { selected } = this.state
return (
<div className="custom-select">
<input
name={this.props.name}
required
style={{ display: "none" }} // or type="hidden", whatever
value={selected
? selected.id
: ""
}
onChange={() => {}}
/>
<div>Selected: {selected ? selected.text : "nothing"}</div>
{this.items.map(item => {
return (
<button
key={item.id}
type="button"
onClick={() => this.handleSelect(item)}
>
{item.text}
</button>
)
})}
</div>
)
}
}
class Form extends React.Component {
handleChange = (event) => {
console.log("Form onChange")
}
render() {
let self = this.handleChange;
let children = React.Children.map(this.props.children, (child, i) => {
if(typeof child.type === "function"){
return React.cloneElement(child, {
onChange: {self}
});
}
return child;
});
return (
<form onChange={this.handleChange}>
{children}
</form>
)
}
}
ReactDOM.render(
<Form>
<label>This input will trigger form's onChange event</label>
<input />
<CustomSelect name="kappa" />
</Form>,
document.getElementById("__root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="__root"></div>
Update your CustomSelect component with the following:
class CustomSelect extends React.Component {
...
// you'll use this reference to access the html input.
ref = React.createRef();
handleSelect = item => {
this.setState({ selected: item });
// React overrides input value setter, but you can call the
// function directly on the input as context
const inputValSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
).set;
inputValSetter.call(this.ref.current, "dummy");
// fire event
const ev = new Event("input", { bubbles: true });
this.ref.current.dispatchEvent(ev);
};
...
render() {
...
return (
<div className="custom-select">
<input
// you'll use the reference in `handleSelect`
ref={this.ref}
name={this.props.name}
required
style={{ display: "none" }} // or type="hidden", whatever
value={selected ? selected.id : ""}
onChange={() => {}}
/>
...
</div>
);
}
...
}
And your Form component with the following:
class Form extends React.Component {
handleChange = event => {
console.log("Form onChange");
// remove synthetic event from pool
event.persist();
};
...
}

How to hide all the div while showing the one which is clicked, in React?

I'm generating some identical div through a list. Below is the sample code.
I'm toggling this div
class App extends React.Component {
state = { showKitten: false };
handleToggleKitten = () => {
this.setState((prevState, props) => ({
showKitten: !prevState.showKitten,
}));
};
render() {
return (
<About
data={datalist}
showKitten={this.state.showKitten}
handleToggleKitten={this.handleToggleKitten}
/>
);
}
}
const About = ({ datalist, showKitten, handletogglekitten }) => {
return (
<div>
{datalist.map((item, index) => {
return (
<div key={index}>
<div onClick={handletogglekitten} />
showKitten ? <div /> : null
</div>
);
})}
</div>
);
};
I have defined tooglefunction and the flag state variable in parent and passing them to children and in children component, I'm creating this divs by iterating over a list. Right now I am able to achieve the toggle functionality for the individual div set but I want to hide all the div and show the one which is clicked.
You could use the index value. Here's a working example.
const datalist = ["cat 1", "cat 2", "cat 3"];
class App extends React.Component {
state = { showKittenIndex: null };
render() {
return (
<About
datalist={datalist}
showKittenIndex={this.state.showKittenIndex}
toggleKitten={index => this.setState({ showKittenIndex: index })}
/>
);
}
}
const About = ({ datalist, showKittenIndex, toggleKitten }) => (
<div className="about">
{datalist.map((item, index) => (
<div key={index}>
<button onClick={() => toggleKitten(index)}>toggle {index}</button>
{showKittenIndex === index && <div>{item}</div>}
</div>
))}
</div>
);
I have a very similar approach than #Kunukn.
But I don't see the need to wrap it in a functional component.
import React, { Component } from 'react';
const elements = ['DIV #1', 'DIV #2', 'DIV #3', 'DIV #4', 'DIV #5', 'DIV #6'];
class App extends Component {
constructor(props) {
super(props);
this.state = {
activeElement: null,
allElements: elements,
};
}
render() {
return (
<About
elements={this.state.allElements}
showIndex={this.state.activeElement}
toggleIndex={index => this.setState({ activeElement: index })}
/>
);
}
}
const About = ({ elements, showIndex, toggleIndex }) => (
<div className="about">
{elements.map((element, index) => (
<div key={index}>
<div onClick={() => toggleIndex(index)}>toggleIndex {index}</div>
{showIndex === index && <div>{element}</div>}
</div>
))}
</div>
);
export default App;
I did write a little clickHandler ... I know that it is not needed at the moment, but when you would want to alter the data received with the click-event this could be handled there as well.
EDIT
According to the comment I improved the code a bit by making a functional component showing the DIVs. I did also dismiss the clickHandler() function.

Mapping over arrays in React

I'm mapping over each object inside the array of objects inside my state's item property. The issue is, I want to be able to attach a button to each returned item that only works with that item, and not the other items too. Here's what I have so far:
class App extends React.Component {
state = {
item: [],
}
componentDidMount() {
this.setState({
item: [
{
name: 'jacob',
hair: 'brown',
sex: 'male',
}, {
name: 'hannah',
hair: 'brown',
sex: 'female',
}
]
})
}
handleChange = (e) => {
console.log(e.target.value)
var x = Object.assign({}, this.state)
}
render() {
return(
<div>
{ this.state.item.length > 0 ?
(
<div className="row mt-5">
<Item item={ this.state.item } handleChange={ this.handleChange } />
</div>
) : null
}
</div>
)
}
}
class Item extends React.Component {
render() {
return(
<div className="col">
{ this.props.item.map(s => (
<div>
<div className="mt-5">{ s.name }</div>
<button onClick={ this.props.handleChange } value={ s.name }>Click</button>
</div>
))}
</div>
)
}
}
So for instance, if the button's fx was to change the name property of the item it was rendered with, I want it to only change that item and no other items should be affected. Whenever I iterate through it attaches the button's fx to every item, so if I click it for one, I'm really clicking it for all of them, and that's exactly what I don't want.
For those curious, I'm setting the state in componentDidMount to simulate calling an API.
Also, the fx that's currently running in the handleChange is just some messing around I was doing trying to figure out values and a solution to manipulating a nested object inside an array.
Try this refactored code on CodeSandBox,
You have to add keys when iterating Components in React, i've added it, also the Item Component could be function Component since it doesn't handle a state.
Updated: below is the code in case it wouldn't be available on codesandbox.
import React from 'react';
import { render } from 'react-dom';
class App extends React.Component {
state = {
items: [],
}
componentDidMount() {
this.setState({
items: [
{
name: 'jacob',
hair: 'brown',
sex: 'male',
}, {
name: 'hannah',
hair: 'brown',
sex: 'female',
}
]
})
}
handleChange = (e) => {
console.log(e.target.value)
}
render() {
const { items } = this.state;
return (
<div>
{items.length && (
items.map((item, index) => (
<div className="row mt-5" key={index}>
<Item item={item} handleChange={this.handleChange} />
</div>
))
)
}
</div>
)
}
}
const Item = ({ item, handleChange }) => (
<div className="col">
<div className="mt-5">{item.name}</div>
<button onClick={handleChange} value={item.name}>Click</button>
</div>
);
render(<App />, document.getElementById('root'));
I think you want to pass the individual element in to your handleChange:
{ this.props.item.map((s, i) => {
<div>
<div className="mt-5">{ s.name }</div>
<button key={i} onClick={ (s) => this.props.handleChange(s) } value={ s.name }>Click</button>
</div>
})}
This way, you will have the individual item passed in as an argument, so when you are writing your handleChange, you can do whatever you want with just that item and not the whole array.

Categories

Resources