React-Router with child in Go how does it work? - go

I'm trying to use react-router with a server in Go.
I did some tests but I can not do what I want.
My react components :
var App = React.createClass({
render: function(){
return (
<div>
<h2>App</h2>
<li><Link to="/page1">Page 1</Link></li>
<li><Link to="/page2">Page 2</Link></li>
</div>
)
}
})
var Page1 = React.createClass({
render: function(){
return (
<div>
<h2>Page 1</h2>
<li><Link to="/page2">Page 2</Link></li>
</div>
)
}
})
var Page2 = React.createClass({
render: function(){
return (
<div>
<h2>Page 2</h2>
<li><Link to="/page1">Page 1</Link></li>
</div>
)
}
})
My react routing :
ReactDOM.render((<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
</Router>), document.getElementById('app'))
my go server :
func Render(c web.C, w http.ResponseWriter, r *http.Request) {
RenderHTMLPage(w, "index.html")
}
func main() {
goji.Get("/page1", Render)
goji.Get("/page2", Render)
goji.Get("/", Render)
goji.Serve()
}
My problem is when i click on Link in 'App' Component, for example :
<li><Link to="/page1">Page 1</Link></li>
url changes like that
http://localhost:8000/page1
But actual component is already App and not Page1, so url changes but not component.
And if i load directly url, i have the same result.
Does anyone help me ?
Thank's :)

This isn't a go question, but a react question, you need to render the App component's children in order for the other two components to display, a la this code snippet taken from the docs for React Router (https://github.com/reactjs/react-router/blob/master/docs/API.md#props-2):
const routes = (
<Route component={App}>
<Route path="groups" component={Groups} />
<Route path="users" component={Users} />
</Route>
)
class App extends React.Component {
render () {
return (
<div>
{/* this will be either <Users> or <Groups> */}
{this.props.children}
</div>
)
}
}

Related

addEventListener for a specific element

I have 2 components routes (Accueil & Apropos):
<Route path='/' element={<Accueil />} />
<Route path='/Apropos' element={<Apropos />} />
I used a scroll eventlistener in the component Accueil as:
useEffect(() => {
const handleScroll = () => {
console.log(document.getElementById('presentation').offsetTop)
}
window.addEventListener("scroll", handleScroll)
return () => { window.removeEventListener("scroll", handleScroll)}
}, [])
but I have a problem, when I switch to the other component, the eventlistener still used and shows that document.getElementById('presentation').offsetTop is null.
How can I use an eventlistener just for my component Accueil ?

How to remove double header with react-navigation?

My React Native 0.61.5 uses react-navigation 5.1. Here is the root navigation code:
const BTab = createBottomTabNavigator();
const Stack = createStackNavigator();
export default function App() {
//const Appscreen = () => (<AppScreen data={data}/>);
return (
<NavigationContainer>
<Stack.Navigator InitialRouteName="Splash">
<Stack.Screen name="Splash" component={SplashScreen}}/>
<Stack.Screen name="App" component={AppScreen} } />
</Stack.Navigator>
</NavigationContainer>
);
}
The component AppScreen return a stack like this:
return (
<NavigationContainer independent={true}>
<BTab.Navigator>
<BTab.Screen name="Event" component={Eventstack} />
<BTab.Screen name="Group" component={Groupstack} />
<BTab.Screen name="Contact" component={Contactstack} />
</BTab.Navigator>
</NavigationContainer>
);
I notice that on the screen there are double header:
How can I remove the App header and only keep the Group?
add with the screen that you want to hide the header.
options= {{
headerShown: false
}}
For further reading, kindly have a look at https://reactnavigation.org/docs/stack-navigator/#headershown

how can i prevent access to routes in react js

I am using react-redux for changing the state in my app.In my router page how can I route based on conditions.ie,If the user logged status is true then if i go to the login component it must redirect to the home component and the user logged status is false,if i go to the home component it must redirect to the login component.
routes.js
const routes=() => (
<Router>
<div>
<Header />
<Route exact path="/" render={ props => <div><FirstConnectedComponent /><SecondConnectedComponent /></div>} />
<Route path="/login" component={ requireAuth(Login) } />
<Route path="/register" component={ UserReg } />
<Route path="/home" component={ Home } />
<Footer />
</div>
</Router>
)
export default routes;
How about creating a new route component called PrivateRoute
PrivateRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
localStorage.getItem('authenticated')
? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)} />
)
index.js
First import it then use -
<PrivateRoute path="/" component={MyComponent} />
You can add a function call :
onEnter={this.requireAuth.bind(this)}
And the function could be something like this :
requireAuth(nextState, replace) {
if (this.user === undefined || this.user === null) {
replace('/login');
}
}

How to work with axios.put and react?

I am trying create a simple crud system with react redux and form-redux.
The code below but does not work and gives error.
First I created an action for update and then created a reducer for that.
And then created component to use the action.
Let me know how to get this to work.
//-------------action--------------
export const EDIT_POST = 'EDIT_POST';
export const editPost = (id) => {
const request = axios.put(`${BOOK_URL}/books/${id}`);
return {
type: EDIT_POST,
payload: id,
}
};
//---------------- reducer-----------------
case EDIT_POST: {
return {...state, post: action.payload.data}
}
//----------------route--------------
<Route path='/posts/edit/:id' component={PostEdit}/>
//-------------------PostEdit---------------
class PostEdit extends Component {
componentDidMount = () => {
this.props.editPost(this.props.match.params.id);
console.log(this.props.editPost(this.props.match.params.id));
};
renderField = field => {
const {meta: {touched, error}} = field;
const className = `form-group ${touched && error ? 'has-danger' : ''}`;
return (
<div className='has-danger'>
<label>{field.label}</label>
<input type="text" {...field.input} className="form-control"/>
<div className="text-help">
{touched ? error : ''}
</div>
</div>
);
};
render() {
const {handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmitForm)}>
<Field name="title" label="Title" component={this.renderField}/>
<Field name="author" label="Author" component={this.renderField}/>
<Field name="description" label="Description" component={this.renderField}/>
<Field name="publicationDate" label="PublicationDate" component={this.renderField}/>
<button type='submit' className="btn btn-primary">Submit</button>
<Link to='/' className='btn btn-danger'>Cancel</Link>
</form>
);
}
}
export default reduxForm({
form :'updateForm'
})(connect(null, {editPost})(PostEdit));
<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>
Could you tell what error you are getting?
You have to change your action like
export const fetchPosts = () => {
return (dispatch) => {
axios.get(`${BOOK_URL}/books`).then((response) => {
return dispatch({
type: FETCH_POSTS,
payload: // your response here
});
})
}
}

react-router-dom v4 link to nested route too much recursion

Currently whenever I try to link to a nested route that renders a new element, I get the too much recursion error. For obvious reasons it keeps rerendering this component. Where does one put a nested route so it doesnt get rendered over and over again?
redirectAddSurvey(){
this.props.addSurvey("Titel Survey", "Survey beschrijving"); this.props.history.push(`/survey/${this.props.match.params.action}`);
}
render() {
return (
<div id="newSurveyButton">
<RaisedButton containerElement={ <Link to={`${this.props.match.url}/new`} />} label="Add new Survey" onClick={() => this.redirectAddSurvey()}></RaisedButton>
<Route path={`${this.props.match.url}/:action`} render={props => <Survey title="Helloworld" desc="HelloDesc" {...props} />} />
</div>
);
}
}
// Get apps state and pass it as props to SurveyList
// > whenever state changes, the SurveyList will automatically re-render
function mapStateToProps(state) {
return {
surveys: state.surveys,
};
}
Updated:
render() {
return (
<div id="newSurveyButton">
<RaisedButton label="Add new Survey" onClick={() => this.redirectAddSurvey()}></RaisedButton>
<Link to={`${this.props.match.url}/new`} />
<Route path={`survey/:action`} render={props => <Survey title="Helloworld" desc="HelloDesc" {...props} />} />
</div>
);
}

Resources