react way of setting focus on a particular button in stateful component? - reactjs

I tried different ways of setting focus to button on pageload like ref ,but it doesnt work. Thats is whenever pageloads focus should be on this button.
Can anyone help me with a sample example
class SubPageHeader extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
}
render() {
return (
<input type="button"/>
);
};
}
Can anyone help me with a solution ?

componentDidMount will execute only once when your page loads first time, to maintain a focus on every re-render you also need to use componentDidUpdate.
class SubPageHeader extends React.Component {
constructor(props) {
super(props);
this.myInput = React.createRef();
}
componentDidMount() {
this.myInput.current.focus(); //To focus first time page loads
}
componentDidUpdate(){
this.myInput.current.focus(); //To focus on every re-render
}
render() {
return (
<input type="button" ref={this.myInput} />
);
};
}

Using refs:
class Component extends React.Component{
input = React.createRef()
componentDidMount(){
this.input.current.focus()
}
render(){ return <input ref={this.input} /> }
}
Or plain HTML : <input autoFocus />

To focus on component mount the simplest way is
class SubPageHeader extends React.Component {
render() {
return (
<input autoFocus type="button"/>
);
};
}

Related

Get value from input component and use it in another component in React

I'm new to React and have this simple code example where I simply need to take value from input and show the value back.
class App extends React.Component {
constructor(props){
super(props);
this.state = { word : ""};
this.onClick = this.onClick.bind(this);
}
onClick(e){
this.setState({word : /* how to obtain input value?? */});
}
render() {
return (
<>
<form>
<input type="text"/>
<button onClick={this.onClick}>Say it!</button>
</form>
<div>
{this.state.word}
</div>
</>
);
}
}
I know react want's me to use component state as a way to propagate information from parent component to it's children. What I don't know is how I should obtain state of a children to be used in another children.
I believe this should be doable in react in simple manner as the equivalent way of doing it using pure DOM or JQuery would also be very simple (one or two lines of code).
You can use createRef
import React, { createRef } from "react";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { word: "" };
this.onClick = this.onClick.bind(this);
}
textInput = createRef();
onClick(e) {
this.setState({ word: this.textInput.current.value });
}
render() {
return (
<div className="App">
<form>
<input ref={this.textInput} type="text" />
<button onClick={this.onClick} type="button">
Say it!
</button>
</form>
<div>{this.state.word}</div>
</div>
);
}
}
export default App;
check here CodeSandBox
A few things here. First I don't see children as you mention. Moreover, you say obtain state of a children to be used in another children. You have just one parent component here. Then, you are using a <form> which means a button inside will submit the values so you need the escape hatch of e.preventDefault(). Finally, if you must use a class based component instead of functional component, you don't need any more constructor and you can bind your functions with an arrow function. Here is a working example of what I presume you are asking: https://codesandbox.io/s/sleepy-minsky-giyhk

want to pass values to parent component from child then wana get those value into another child component

this is my parent component
class App extends Component {
constructor()
{
super();
this.state={counter:1,yourid:'',yourname:'',yourgender:''};
this.handleLogin=this.handleLogin.bind(this);
this.userview=this.userview.bind(this);
this.going=this.going.bind(this);
}
going(id,name,gender)
{
console.log("THIS IS DONE BY REACT GEEK:",id,name,gender);
this.setState({yourid:id,
Yourname:name,
Yourgender:gender});
}
this is my app.js render funtion
<Login passingvalue={this.going} />
<MessageView LoggedInUser={this.going} />
and here is my first child components from where i send values
export default class Login extends Component {
constructor(props)
{
super(props);
this.state={
id:'',name:'',gender:''
}
this.show = this.show.bind(this);
this.sendingvalue=this.sendingvalue.bind(this)
}
sendingvalue()
{
this.props.passingvalue(this.state.id,this.state.name,this.state.gender);
// console.log('passing',Id);
console.log('hello this is going ',
this.state.id,
this.state.name,
this.state.gender)
}
and again here is my second child component where i want these values
export default class Messageonline extends Component {
constructor(props)
{
super(props);
this.state = {Id:this.props.LoggedInUser.yourid,
Name:this.props.LoggedInUser.yourname,
Gender:this.props.LoggedInUser.yourgender};
}
render() {
return (
<div className="messageshow">
<div className="row">
<div className="col-lg-10 "id="message_show">
<h3>Inbox</h3>
</div>
<div className="col-lg-2" id="online_user" >
<h3>online Users</h3>
<span>{this.state.Id}</span>
<br/>
<span>{this.state.Name}</span>
<br/>
<span>{this.state.Gender}</span>
</div>
</div >
</div>
there is any mistake thats why i cannot get those values in my second child..whats is that mistake i dont know ..tell me whats this mistake i want to fix that as soon as possible..thanks
Looks like you are passing the going method as the LoggedInUser prop to your MessageView component:
<MessageView LoggedInUser={this.going} />
You are probably looking to pass a user object instead.
Something like this:
<MessageView LoggedInUser={{
yourid: this.state.yourid,
yourname: this.state.yourname,
yourgender: this.state.yourgender
}} />

How to render a redux connected component in a modal

I am trying to add authentication to my react redux app, and I want to use modals for the login and signup pages. I have a LoginForm and a SignupForm which are static components, and I have LoginPage and SignupPage, which are my container components for the forms.
I am currently able to render the container components using login and signup routes, but I want switch to using modals.
Please how do I do this using a modal, say, react-materialize modal or normal materialize css modal?
Thanks for the help.
Revisiting this answer, I would say you need to have two components able to communicate. This is the plain React way to do this. Notice there is one App component with two sibling components. By passing a props value to the Modal component and a props callback to its sibling, we can get the modal to render or not render.
class Modal extends React.Component {
render() {
return this.props.modalShow ? (
<div className="modal">
Modal loaded
</div>
) : null;
};
};
class Sibling extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.openModal();
}
render() {
return (
<div>
I am a sibling element.
<button onClick={this.handleClick}>Show modal</button>
</div>
)
};
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
modalShow: false,
};
this.openModal = this.openModal.bind(this);
};
openModal() {
this.setState({ modalShow: true });
}
render() {
return (
<div>
<Modal modalShow={this.state.modalShow} />
<Sibling openModal={this.openModal}/>
</div>
)
};
};
ReactDOM.render(
<App />,
document.getElementById('app')
);
From here, using Redux is much simpler since the state is "global" already. But the idea is the same. Instead of having a parent control the state, just use your reducers and actions. I hope this helps.

how to add various types of elements to dom reactjs?

i have a toolbar component and 3 options to add text, image and video element to main page component, i write a click handle in main page component and pass this event handler to toolbar component.
my simple idea is that a switch with a parameter that define the type of element but i don't know how to render them.
how can i do this?
class ToolbarContainer extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div id="toolbarSection">
<div class="option" onClick={this.props.handleActionsClick("image")}>new Image</div>
<div class="option" onClick={this.props.handleActionsClick("text")}>new Text</div>
<div class="option" onClick={this.props.handleActionsClick("shape")}>new Shape</div>
</div>
);
}
}
class Page extends React.Component {
constructor(props) {
super(props);
}
handleActionsClick(type){
switch(type){
case "image":
//How can i render the <img/>?
case "text":
case "video":
}
}
render() {
return ();
}
}
Use createElement instead, which is what JSX uses under the hood.
You can then pass in a custom component to the click handler or a string for the native elements like 'img'.
I am using stateless component here but you can also just use classes if you need.
const ToolBarContainer = ({ handleActionsClick }) => (
<div id="toolbarSection">
<div class="option" onClick={handleActionsClick('img')}>new Image</div>
<div class="option" onClick={handleActionsClick(Text)}>new Text</div>
<div class="option" onClick={handleActionsClick(Shape)}>new Shape</div>
</div>
);
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleActionsClick = this.handleActionsClick.bind(this);
}
handleActionsClick(type){
this.setState({ type });
}
render() {
return React.createElement(this.state.type);
}
}

What is the purpose of this.props.onChange()?

From the react quickstart: https://facebook.github.io/react/docs/lifting-state-up.html
The purpose of the line:
handleChange(e) {
this.props.onChange(e.target.value);
}
was never explained and I can't figure out what it does. Is onChange a built in method of props? I thought props was simply just parameters for components, why can it invoke functions?
I came here with the same question, but I understand it now (at least I think I do). The issue is that onChange in the Calculator class is a prop, but in the render portion of the class TemperatureInput, it's an event listener. Sometimes I see this in React, where the same name is used on two completely different things, and I find it can easily create confusion. Here's what happens in the following code block:
class TemperatureInput extends React.Component {
handleChange(e) {
this.props.onChange(e.target.value); **(2)**
}
render() {
return (
<fieldset>
<input value={value} onChange={this.handleChange} /> **(3)**
</fieldset>
);
}
}
class Calculator extends React.Component {
handleCelsiusChange(value) {
this.setState({scale: 'c', value});
}
render() {
return (
<div>
<TemperatureInput
scale="c"
value={celsius}
onChange={this.handleCelsiusChange} /> **(1)**
</div>
);
}
}
In Calculator, a made up prop called onChange passes a reference to the method handleCelsiusChange to TemperatureInput
this.props.onChange() in TemperatureInput is now a reference to handleCelsiusChange() in Calculator
onChange={this.handleChange} is an event listener, which will fire handleChange() up on the change of the input field.
In conclusion, onChange as a prop is custom, onChange as an event listener is built in. The prop just passes a function reference from an ancestor to the child so you can run it in the child.
I thought props was simply just parameters for components, why can it invoke functions?
You're right, but those parameters can also be callbacks/functions. E.g:
Definition:
class Comp extends Component {
handleChange(e) {
this.props.onChange(e.target.value);
}
render() {
return (<input onChange={this.handleChange.bind(this)) />
}
}
Usage:
<Comp onChange={(a) => console.log(a)} />
Got a clue from SeattleFrey's answer, maybe the author of that code shouldn't name this parameter onchange. It is so confusing for a starter of ReactJs like me.
I name it myChange instead of onChange. It is actually a function passed in as a parameter. And e.target.value is the parameter for that function.Props can contain objects as well as functions, since functions are also objects in Javascript
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.myChange(e.target.value);
}
render() {
const value = this.props.value;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={value}
onChange={this.handleChange} />
</fieldset>
);
}
}
class Calculator extends React.Component {
handleCelsiusChange(value) {
this.setState({scale: 'c', value});
}
render() {
return (
<div>
<TemperatureInput
scale="c"
value={celsius}
myChange={this.handleCelsiusChange} />
</div>
);
}
}
You just missed this sentence:
If several components need access to the same state, it is a sign that the state should be lifted up to their closest common ancestor instead. In our case, this is the Calculator.
Your quoted code is from component TemperatureInput:
class TemperatureInput extends React.Component {
handleChange(e) {
this.props.onChange(e.target.value);
}
render() {
return (
<fieldset>
<input value={value} onChange={this.handleChange} />
</fieldset>
);
}
}
And TemperatureInput is a child component of Calculator, where TemperatureInput.onChange is assigned to Calculator. handleCelsiusChange
class Calculator extends React.Component {
handleCelsiusChange(value) {
this.setState({scale: 'c', value});
}
render() {
return (
<div>
<TemperatureInput
scale="c"
value={celsius}
onChange={this.handleCelsiusChange} />
</div>
);
}
}

Resources