How to render dynamic components onClick - reactjs

My code creates dynamic components/elements based on size of list of entities (in cache/memory). How can I modify this so that the onClick on line 32 (fab-click) adds yes another entity to the list. I ommitted the MainMenuElement class so lets assume it works. I think this is a problem of not knowing how to "think in react". Must I use react's state to achieve this, or is there a cleaner way?
I am actually adapting this from an HTML5/CSS3 app which used and am finding this to be much harder than just appending children from anywhere/any-time like with templates. Help.
createMainMenuElement(conversation){
return <MainMenuElement conversation = {conversation} key ={conversation.key} />
}
createMainMenuElements(conversations) {
return conversations.map(this.createMainMenuElement)
}
generateData = function(){
let usernames = ["tony","john","doe","test", "bruce"]
let data = [];
for(let i = 0; i < 5; i++){
let temp = {key: i.toString(), username: usernames[i], timestamp: "4:30", subtitle: "The quick brown fox jumps over the lazy dog"}
data.push(temp)
this.mainMenuStack+=1;
}
return data;
};
handleFabClick() {
console.log("test")
let temp = {key:this.mainMenuStack.toString(), username: "Baby", timestamp: "12:30", subtitle: "The quick red cat jumps over the yellow dog"};
this.createMainMenuElement(temp);
};
render(){
return(
<div className={cx('mainMenu')}>
<div className={cx('mainMenu__element','mainMenu__element--pseudo')} onClick={this.handleFabClick}>
<div className={cx('mainMenu__element__icon fab')} id="fab">
<div className={cx('fab__icon')}>+</div>
</div>
<div className={cx('mainMenu__element__textWrapper')}>
<div className={cx('mainMenu__element__title')}>New Conversation</div>
</div>
</div>
{this.createMainMenuElements(this.generateData())} //WORKS ON LOAD
//WANT TO RENDER/APPEND DYNAMIC COMPONENTS HERE
</div>
)
};
}

You're thinking about the DOM, when you need to think about the data. In React, the DOM is purely a function of your data.
You'll need to store the dynamically created data, let's use an array
constructor(props){
super(props)
this.state = {
elements:[]
}
}
Then render the data. elements is empty for now, that's fine. But we know that eventually, the user will create data dynamically. The render function already handles that!
render(){
return (
<div>
//other code
{this.state.elements.map(this.createMainMenuElement)}
</div>
)
}
Now let's add the data.
handleFabClick() {
let temp = {key:this.mainMenuStack.toString(), username: "Baby", timestamp: "12:30", subtitle: "The quick red cat jumps over the yellow dog"};
this.setState({
elements: [...this.state.elements, temp]
})
};
We've now changed the state of the component, which causes it to rerender, which will display the new data. No DOM operations needed!
My code does not translate directly to your question, i'm merely showing you the React fundamentals. You said that you want to add elements to an existing list, so it looks like elements needs to contain ["tony","john","doe","test", "bruce"] by default. I hope you get the point though.

Related

How to query and update the DOM with yew?

Is there any way to make DOM action via use_node_ref? or alternatively, how to do document.query_selector() in Rust using yew?
use web_sys::HtmlInputElement;
use yew::{
function_component, functional::*, html,
NodeRef, Html
};
#[function_component(UseRef)]
pub fn ref_hook() -> Html {
let input_ref = use_node_ref();
let all_editables = input_ref.query_selector("[contenteditable]")
web_sys::console::(all_editables)
html! {
<div>
<input ref={input_ref} type="number" />
</div>
}
}
Goal: I have a rich text editor app. And I have a minified html in form of string like this <h1> this is title</h1><p>hello world</> and I need to get the DOM and change the innerHTML to set it to this value.
Goal2: I will also need to update the innerHtml as the user write things in the contenteditable elements. Fore example when the user type #john smith I will make a create an <a> element with href the have the link to John smith's profile.
Many things to tackle with your question.
#1 Do not set inner html
More to read about this in Alternative for innerHTML?
But instead create text nodes.
So using web-sys you would do something like:
let txtNode: Node = window()
.unwrap_throw()
.document()
.unwrap_throw()
.create_text_node("Hello")
.dyn_into()
.unwrap_throw();
myDomElement.append_hild(&txtNode).unwrap_throw();
#2 How to query data from an input
There are many ways to do this so ill just show you one of them -
controlled input
core idea is keep your input value in use_state and sync it with the input element using value and oninput attributes.
#[function_component(ControlledInputComponent)]
pub fn controlled_input_component() -> Html {
let my_text_handle = use_state(|| "".to_string());
let my_text = (*my_text_handle).clone();
let handle_input = Callback::from(move |input_event: InputEvent| {
let event: Event = input_event.dyn_into().unwrap_throw();
let input_elem: HTMLInputElement = event.target().unwrap_throw().dyn_into().unwrap_throw();
let value = input_elem.value();
my_text_handle.set(value); // update as user types
});
html! {
<div>
<input type="text" value={my_text} oninput={handle_input} />
</div>
}
}
#3 Update DOM
**External to yew as you should generally avoid updating DOM that is controlled by yew
You can then use use_effec_with_deps to react to your input changing and update your external preview there
let my_text_handle = use_state(|| "".to_string());
let my_text = (*my_text_handle).clone();
use_effect_with_deps(move |my_text| {
// run all the code from my tip #1 like:
// myDomElement.append_hild(&txtNode).unwrap_throw();
||{}
}, my_text);

Creating a looped HTML element in React

I'm relatively new to React, I've looked a lot of places and can't find a way to specifically handle this. I have checked previous answers.
I am trying to get my application to loop through an array and also print a statement along with the array.
var user = ["Kevin", "Kyle", "Kylian"];
var Hello = <h1>
Hello, {user}!
</h1>
class App extends Component {
render() {
for(var i=0;i<user.length;i++){
return Hello;
}
}
}
export default App;
Output:
Hello, KevinKyleKylian!
Expected Output:
Hello, Kevin!
Hello, Kyle!
Hello, Kylian!
As you can see, the loop for some reason doesn't continuously return the entire output and after the user iteration of {user} it just prints {user} until the array is ended. Why does this happen? How can I avoid this?
It's probably because of this bit:
var Hello = <h1>
Hello, {user}!
</h1>
In that case 'user' is referring to the whole array, not just a specific element of that array.
Generally, if you're building elements dynamically in React it's good to put that in a separate function rather than the render method, I feel it's a bit neater. So something like this:
getUsers() {
let userList = [];
for (let i=0; i<user.length; i++) {
userList.push(<div>Hello, {user[i]}</div>);
}
return userList;
}
render() {
return(
<div>
{this.getUsers()}
</div>
);
}

ReactJS parent/child list items not rendering properly after an item is removed

Example: https://jsfiddle.net/wbellman/ghuw2ers/6/
In an application I am working on, I have a parent container (List, in my example) that contains a list of children (Hero, in my example). The list is governed by an outside object. For simplicity I declared the object directly in the JS. (In my real application the data store is properly namespaced and so forth.)
The problem I have is in the list I have three elements, if I remove an item from the middle, the rendered list appears to remove the last element. However the outside object reflects the proper list.
For example:
My list has the elements: cap, thor, hulk
If you remove "thor", "cap" and "thor" are rendered
The heroList reflects "cap" and "hulk" as it should
I am relatively new to ReactJs, so there is a good chance my premise is fundamentally flawed.
Note: The example reflects a much more complex application. It's structured similarly for purposes of demonstration. I am aware you could make a single component, but it would not be practical in the actual app.
Any help would be appreciated.
Here is the code from JSFiddle:
var heroList = [
{ name: "cap" },
{ name: "thor"},
{ name: "hulk"}
];
var List = React.createClass({
getInitialState() {
console.log("heros", heroList);
return {
heros: heroList
};
},
onChange(e){
this.setState({heros: heroList});
},
removeHero(i,heros){
var hero = heros[i];
console.log("removing hero...", hero);
heroList = _.filter(heroList, function(h){ return h.name !== hero.name;});
this.setState({heros:heroList});
},
render() {
var heros = this.state.heros;
var createHero = (hero,index) => {
return <Hero hero={hero} key={index} onRemove={this.removeHero.bind(this,index,heros)}/>;
};
console.log("list", heros);
return (
<ul>
{heros.map(createHero)}
</ul>
)
}
});
var Hero = React.createClass({
getInitialState() {
return {
hero: this.props.hero
}
},
render() {
var hero = this.state.hero;
return (
<li>Hello {hero.name} | <button type="button" onClick={this.props.onRemove}>-</button></li>
);
}
});
ReactDOM.render(
<List />,
document.getElementById('container')
);
Additional: I was having problems copying the code from JSFiddle, anything I broke by accident should work in the JSFiddle listed at the top of this question.
Edit:
Based on the commentary from madox2, nicole, nuway and Damien Leroux, here's what I ended up doing:
https://jsfiddle.net/wbellman/ghuw2ers/10/
I wish there was a way to give everyone credit, you were all a big help.
Changing your Hero class to this fixed the issue of displaying the wrong hero name for me:
var Hero = React.createClass({
render() {
return (
<li>Hello {this.props.hero.name} | <button type="button" onClick={this.props.onRemove}>-</button></li>
);
}
});
i.e. I removed the local state from the class and used the prop directly.
Generally speaking, try to use the local store only when you really need it. Try to think of your components as stateless, i.e. they get something through the props and display it, that's it.
Along these lines, you should consider passing the hero list through the props to your List component as well.
if you really have problems with managing your data you should use Flux or Redux.
in this code:
heroList = _.filter(heroList, function(h){ return h.name !== hero.name;});
i just dont get why you filer the heroList instead of this.state.heros? every time you add or remove a hero, the heroList in your current scope shouldnt be kept in state? the global heroList is just the initial state.
The problem is with the keys used. Since the key is taken from the index, that key has already been used and thus the hero with that key is shown.
change it to key={Math.random() * 100} and it will work

Get element sibling value in React

I have this method inside a React component (which I later pass to the render() method):
renderNutrientInputs: function (num) {
var inputs = [];
for (var i =0; i < num; i++) {
inputs.push(<div key={i}>
<label>Nutrient name: </label><input type="text"/>
<label>Nutrient value: </label><input type="text" />
</div>);
}
return inputs;
}
I'm trying on each change of the "Nutrient value" textbox, to also grab the current value of the "Nutrient name" textbox. I first though of assigning "ref" to both of them, but I figured there might be multiple pairs of them on the page (and the only way to identify them would be by key). I also tried something like this:
<label>Nutrient name: </label><input type="text" ref="nutName"/>
<label>Nutrient value: </label><input type="text" onChange={this.handleNutrientValueChange.bind(null, ReactDOM.findDOMNode(this.refs.nutName))}/>
but got a warning from React:
Warning: AddForm is accessing getDOMNode or findDOMNode inside its
render(). render() should be a pure function of props and state. It
should never access something that requires stale data from the
previous render
Is there some way to attach onChange event listener to Nutrient value text box and access the current value of "Nutrient name" textbox in the event listener function?
You don't want to access DOM elements directly. There is no need to do so... Work with your data, forget about DOM!
What you want is to "listen to changes to n-th nutritient. I want to know it's name and it's value". You will need to store that data somewhere, let's say in state in this example.
Implement getInitialState method. Let's begin with empty array, let user to add nutritients.
getInitialState() {
return { nutritients: [] };
},
In render method, let user add nutrition by click on "+", let's say
addNutritient() {
const nutritients = this.state.nutritients.concat();
nutritients.push({ name: "", value: undefined });
this.setState({ nutritients });
},
render() {
return (
<div>
<div onClick={this.addNutritient}>+</div>
</div>
)
}
Okay, let's focus on rendering and updating nutritients:
addNutritient() {
const nutritients = this.state.nutritients.concat();
nutritients.push({ name: "", value: undefined });
this.setState({ nutritients });
},
renderNutritients() {
const linkNutritient = (idx, prop) => {
return {
value: this.state.nutritients[idx][prop],
requestChange: (value) {
const nutritients = this.state.nutritients.concat();
nutritients[idx][prop] = value;
this.setState({ nutritients });
},
}
};
const nutritients = [];
return (
this.state.nutritients.map((props, idx) => (
<div>
<input valueLink={linkNutritient(idx, "name")} />
<input valueLink={linkNutritient(idx, "value")} />
</div>
))
)
},
render() {
return (
<div>
{ this.renderNutritients() }
<div onClick={this.addNutritient}>+</div>
</div>
)
}
Coding by hand, sorry for syntax error or typings.
Edit:
Take a look at this working Fiddle https://jsfiddle.net/Lfrk2932/
Play with it, it will help you to understand what's going on.
Also, take a look at React docs, especialy "valueLink" https://facebook.github.io/react/docs/two-way-binding-helpers.html#reactlink-without-linkedstatemixin
I prefer not to use 2 way binding with React which is kind of a flux anti-pattern. Just add a onChange listener to your input element and setState.
Your state will be something like this:
{0: {nutrientName: xyz, nutrientValue: 123},
1: {nutrientName: abc, nutrientValue: 456}}
So when you change the nutrientvalue 456 to say 654, you can say its corresponding name is abc and vice versa.
The whole thing about React is about handling the data not the DOM :)

ReactJS - Listing all keys at once

I'm a beginner of ReactJS and I'm stuck trying to figure out why map only returns a single prop at a time.
In file1.jsx, I have an array that contains 3 objects:
var MainPanelOneData = [{"id":1,"shotviews":15080},{"id":2,"likes":12000},{"id":3,"comments":5100}];
File1.jsx also has a render function to extrapolate the data inside the array:
render: function() {
var ListMainPanelOne = MainPanelOneData.map(function(data) {
return <MainPanelOne key={data.key} shotviews={data.shotviews} likes={data.likes} comments={data.comments} />
});
In file2.jsx, I have this code to render the data object from file1.jsx:
render: function() {
return (
<div>
<span>{this.props.shotviews} shot views</span>
<span>{this.props.likes} likes</span>
<span>{this.props.comments} comments</span>
</div>
)
}
The result shows this:
15080 shot views likes comments
shot views12000 likes comments
shot views likes5100 comments
I'm guessing it repeats like this because it searches through one key at a time? If that's the case, how do I display all keys at the same time? Use indexing?
well your array of data doesnt have all the keys. each one of your objects in PanelOneData has ONE key and is missing the other two; additionally none of them have key called key. so youre making three MainPanelOne components, each with a single prop. the result of that map is this
[
<MainPanelOne key={null} shotviews={15080} likes={null} comments={null} />,
<MainPanelOne key={null} shotviews={null} likes={12000} comments={null} />,
<MainPanelOne key={null} shotviews={null} likes={null} comments={5100} />
]
which is an accurate display of what youre seeing
To get one line you might do something like this.
render: function() {
var ListMainPanelOne = MainPanelOneData.map(function(data) {
return <span key={data.id}> {data.shotviews} {data.likes} {data.comments} </span>
});

Resources